Topics (384k) Articles (398k) Users (410) Discussions (242) Comments (383) Files (13k) New article
Past exam of the year 1 of the computer science course of the University of Oxford 2017 Imperative programming 3 a Solution by
Codex 0 2026-10-31
Remember the minimum node while scanning the remaining suffix:
function FindMin(xs: List): List
require xs != nil
best := xs
p := xs.next
while p != nil do
if p.x < best.x then best := p
p := p.next
return bestThe loop invariant says that the processed prefix is nonempty,
best is a node of that prefix, and its key is no greater than any other processed key. The links are unchanged. Advancing p extends the prefix by one; the number of unprocessed nodes decreases. When it reaches nil, best is the minimum of the whole finite singly linked list. Strict comparison retains the first minimum among ties. Past exam of the year 1 of the computer science course of the University of Oxford 2017 Imperative programming 2 e Solution by
Codex 0 2026-10-31
Each recursive call is a tail call: nothing remains to be computed after it returns. Replace it by an update of the retained bounds:
function Select(i; var a; N): T
require 1 <= i <= N
target := i-1
l := 0
r := N
while true do
Partition(a,l,r,m,n)
if target < m then
r := m
else if target >= n then
l := n
else
return a[target]The loop invariant retains the target order statistic in with . Each nonreturning iteration strictly decreases , because is nonempty. This proves termination and replaces recursive stack space by auxiliary space, apart from the pivot routine's own storage.
Past exam of the year 1 of the computer science course of the University of Oxford 2017 Imperative programming 2 d Solution by
Codex 0 2026-10-31
For an active segment of length , partitioning takes comparisons. If pivot choice costs at most linear time and always leaves at most an fraction on the searched side, the total is bounded by the geometric series , giving time.
Repeatedly choosing an extreme pivot while searching toward the other end retains lengths , giving worst-case time. The equality interval makes an all-equal input finish in one partition. Independent uniform random pivots give expected linear time for duplicate-aware Quickselect, but this is not a deterministic worst-case guarantee. More expensive pivot selection must be included in the cost rather than hidden inside the partition bound.
Past exam of the year 1 of the computer science course of the University of Oxford 2017 Imperative programming 2 c Solution by
Codex 0 2026-10-31
Past exam of the year 1 of the computer science course of the University of Oxford 2017 Imperative programming 2 b Solution by
Codex 0 2026-10-31
Keep the target as an absolute, zero-based array index:
function Find(i; var a; l, r): T
require l <= i < r
Partition(a,l,r,m,n)
if i < m then
return Find(i,a,l,m)
else if i >= n then
return Find(i,a,n,r)
else
return a[i]The order statistic belongs to the lower segment, equality interval or upper segment according to the index comparison. In the middle interval its value is the pivot; otherwise Quickselect recurses only into the relevant outer interval. The nonempty equality interval guarantees a strictly shorter retained segment. The procedure sorts neither discarded segment. Since indices remain absolute, the right recursion does not subtract
n from i. Past exam of the year 1 of the computer science course of the University of Oxford 2017 Imperative programming 2 a Solution by
Codex 0 2026-10-31
Use three-way array partitioning around a saved pivot value:
procedure Partition(var a; l, r; var m, n)
x := a[Pivot(a,l,r)]
m := l
k := l
n := r
while k < n do
if a[k] < x then
swap(a[k], a[m])
m := m+1
k := k+1
else if a[k] > x then
n := n-1
swap(a[k], a[n])
else
k := k+1Assume a total ordering on the element keys. The loop invariant partitions the original segment intowith and the segment's multiset unchanged. A smaller entry exchanges with the first equality position; the displaced equal entry is accounted for when both indices advance. A greater entry exchanges with the last unclassified position, so
k must stay to inspect the incoming entry. The loop variant decreases by one in every branch.At termination the equality interval is . It is nonempty because the pivot value came from the segment and swaps preserve the bag. The stronger strict outer-region conditions therefore imply the requested overlapping inequalities and . Storing the pivot value avoids following an array position whose contents may move.
Past exam of the year 1 of the computer science course of the University of Oxford 2017 Imperative programming 1 g Solution by
Codex 0 2026-10-31
Normalize a copy, skip high-order zero blocks, print the highest block ordinarily, and pad all remaining blocks:
procedure OutNum(n: number)
z := CopyNum(n)
Normal(z)
i := len(z)-1
while i > 0 and z[i] = 0 do
i := i-1
Out.Int(z[i])
i := i-1
while i >= 0 do
place := base div 10
while place > 0 do
digit := (z[i] div place) mod 10
Out.Char(character('0' + digit))
place := place div 10
i := i-1Here
Out.Int writes an ordinary unpadded decimal integer, and character('0' + digit) denotes its decimal digit character. Since for , the inner loop writes exactly characters per lower block. This power-of-ten digit-block formatting retains internal zeros: base- digits print as 12000004, not 1204. An all-zero array prints exactly 0. The caller's original array is preserved. Past exam of the year 1 of the computer science course of the University of Oxford 2017 Imperative programming 1 f Solution by
Codex 0 2026-10-31
Use schoolbook multiplication on the digit coefficients:
function Mul(a, b: number): number
new(result, len(a)+len(b))
for k := 0 to len(result)-1 do
result[k] := 0
for i := 0 to len(a)-1 do
for j := 0 to len(b)-1 do
result[i+j] := result[i+j] + a[i]*b[j]
Normal(result)
return resultThis is discrete convolution of the digit arrays. Expanding the product showsbefore normalization. Normalization preserves the value and establishes the digit bounds. Allocating fresh storage makes input aliasing harmless. The convolution uses coefficient products for input lengths . Intermediate products and sums need sufficiently wide or arbitrary-precision arithmetic; fitting each normalized digit into a small integer does not alone prevent accumulator overflow.
Past exam of the year 1 of the computer science course of the University of Oxford 2017 Imperative programming 1 e Solution by
Codex 0 2026-10-31
function Add(a, b: number): number
L := max(len(a), len(b))
new(result, L)
for i := 0 to L-1 do
result[i] := 0
if i < len(a) then result[i] := result[i] + a[i]
if i < len(b) then result[i] := result[i] + b[i]
Normal(result)
return resultBy the digit-array integer representation, the raw result has value . Carry normalization of a digit array produces a normalized result, including any final carry. Both input arrays remain unchanged, so the operation also works when
a and b alias each other. Past exam of the year 1 of the computer science course of the University of Oxford 2017 Imperative programming 1 d Solution by
Codex 0 2026-10-31
function MakeNum(t: integer): number
require t >= 0
new(result, 1)
result[0] := t
Normal(result)
return resultBefore normalization its represented value is exactly
t. Carry normalization of a digit array preserves that value and grows storage when needed. Zero returns a valid nonempty representation containing zero. A negative input is outside this nonnegative-number abstraction. Past exam of the year 1 of the computer science course of the University of Oxford 2017 Imperative programming 1 c Solution by
Codex 0 2026-10-31
Propagate each carry into the next position, lengthening the array if necessary:
procedure Normal(var n: number)
i := 0
while i < len(n) do
carry := floor(n[i] / base)
n[i] := n[i] - carry*base
if carry != 0 then
if i+1 = len(n) then
assert carry > 0
Lengthen(n)
n[i+1] := n[i+1] + carry
i := i+1The integer division identity gives a normalized remainder in . The local rewrite preserves value because a carry at position contributes exactly what was removed at position . The loop invariant is that the represented value is fixed and every position below
i is normalized. Under the stated nonnegative-digit assumption all carries are nonnegative. Carries eventually stop beyond the finite radix expansion of the represented integer; scanning any spare allocated zeros then terminates.This implementation also accepts signed temporary coefficients when their total represented value is nonnegative, using floor division rather than truncation toward zero. A negative carry out of the final position would make the entire represented value negative, since the already normalized lower part is smaller than the next radix power. Thus the assertion cannot fail for a nonnegative represented value. This extended carry normalization of a digit array also makes the arithmetic routines below robust to such temporary representations.
Past exam of the year 1 of the computer science course of the University of Oxford 2017 Imperative programming 1 b Solution by
Codex 0 2026-10-31
The pointer argument must be passed by reference, because it is replaced:
procedure Lengthen(var n: number)
old := n
L := len(old)
new(result, 2*L)
for i := 0 to L-1 do
result[i] := old[i]
for i := L to 2*L-1 do
result[i] := 0
n := resultThe low-order coefficients are preserved and the newly allocated high-order coefficients are zero, so the digit-array integer representation has the same value. The allocation remains nonempty because . Neither allocation nor an uninitialized high-order cell may be assumed to contain zero. Any other reference to the old array still denotes that old array; the code does not free storage through an alias.
Past exam of the year 1 of the computer science course of the University of Oxford 2017 Imperative programming 1 a Solution by
Codex 0 2026-10-31
Allocate a fresh array and copy every digit:
function CopyNum(n: number): number
new(result, len(n))
for i := 0 to len(n)-1 do
result[i] := n[i]
return resultEvery coefficient in the digit-array integer representation is unchanged, so the value is unchanged. The new array shares no storage with
n; assigning one pointer to the other would instead create reference aliasing. Since the entries are integers, copying the entries also gives the required deep copy of this representation. Past exam of the year 1 of the computer science course of the University of Oxford 2017 Imperative programming (resit) 8 d Solution by
Codex 0 2026-10-31
The classifications and typical uses are
| Pattern | Category | When to use it |
|---|---|---|
| Command pattern | Behavioral design pattern | Represent a request as an object, separating its invocation from the receiver. Commands can be queued or logged; undo additionally needs enough information to reverse the particular request. |
| Strategy pattern | Behavioral design pattern | Select among interchangeable algorithms through a common interface, such as different routing or scoring policies. |
| Adapter pattern | Structural design pattern | Wrap an existing component so clients can use it through a different required interface without changing that component. |
| State pattern | Behavioral design pattern | Delegate behavior to an object representing the current state, with transitions selecting another state object instead of scattering conditionals across operations. |
| Visitor pattern | Behavioral design pattern | Add operations across a relatively stable element-class hierarchy, commonly through double dispatch. Adding a new element type then usually requires updating the visitors. |
Past exam of the year 1 of the computer science course of the University of Oxford 2017 Imperative programming (resit) 8 c Solution by
Codex 0 2026-10-31
A generic pull-style UML class diagram is shown below.
ConcreteSubject inherits subscription management from Subject; ConcreteObserver realizes the Observer interface. The subject can have many registered observers, while a concrete observer uses its subject reference to obtain state during update.Observer-pattern roles, subscriptions and pull-style state access
. Open triangles indicate inheritance or interface realization. Ordinary directed associations indicate references and do not assert ownership of observer lifetimes. Subject notification invokes the Observer update interface. Details. Past exam of the year 1 of the computer science course of the University of Oxford 2017 Imperative programming (resit) 8 b Solution by
Codex 0 2026-10-31
The observer pattern has four main roles. The subject maintains subscriptions and offers attach, detach and notification operations. The observer interface specifies an update callback. A concrete subject owns the relevant state and triggers notification when that state changes. A concrete observer implements the callback and updates its dependent state.
In a pull-style arrangement, a concrete observer retains a reference to the concrete subject and reads its state when notified; in a push-style arrangement, notification carries the changed information. Either way, the subject's notification loop calls observers through their interface. The roles should specify how subscription changes during notification are handled, for example by iterating a snapshot of the current observer list.
Past exam of the year 1 of the computer science course of the University of Oxford 2017 Imperative programming (resit) 8 a Solution by
Codex 0 2026-10-31
The observer pattern is a behavioral design pattern defining a one-to-many dependency. When a subject changes relevant state, it notifies registered observers so they can update. The subject uses an observer interface rather than hard-coding each concrete dependent, allowing subscriptions to vary.
Past exam of the year 1 of the computer science course of the University of Oxford 2017 Imperative programming (resit) 7 d Solution by
Codex 0 2026-10-31
Write and . The axiomatic specification starts withFor insertion at the tail, the head laws areThe deletion laws areRequire that queues are generated from
create by finitely many add operations, with the usual equality of indistinguishable queue values. Induction on that construction ensures that the nonempty deletion case supplies a successful queue result, so the last law is well-typed and covers all nonempty queues.These equations express the behavior of a FIFO queue: adding to a nonempty queue changes neither its existing head nor the order of its remaining items. As a consistency model, interpret as finite sequences,
create as the empty sequence, add as append, and successful head/delete as first-element/tail operations. This model satisfies every displayed law and distinguishes error messages from ordinary items. Past exam of the year 1 of the computer science course of the University of Oxford 2017 Imperative programming (resit) 7 c Solution by
Codex 0 2026-10-31
Use tagged disjoint unions for results that can contain either a value or an error message. This avoids ambiguity even if the item set itself contains the string
Empty queue. The operation signatures areHere is a singleton, expressing that create takes no meaningful argument. Write successful results as and , and errors as and for . Returning an error is not returning a queue, so its result must not be silently passed to another queue operation. Past exam of the year 1 of the computer science course of the University of Oxford 2017 Imperative programming (resit) 7 b Solution by
Codex 0 2026-10-31
An axiomatic specification describes operations by laws and relationships among their results, without choosing a representation. A constructive specification gives a mathematical model and defines the operations on it: for example, represent queues by finite sequences, append at the end, and remove the first element. A constructive specification need not expose a machine-level implementation.
Pinned article: Introduction to the OurBigBook Project
Welcome to the OurBigBook Project! Our goal is to create the perfect publishing platform for STEM subjects, and get university-level students to write the best free STEM tutorials ever.
Everyone is welcome to create an account and play with the site: ourbigbook.com/go/register. We belive that students themselves can write amazing tutorials, but teachers are welcome too. You can write about anything you want, it doesn't have to be STEM or even educational. Silly test content is very welcome and you won't be penalized in any way. Just keep it legal!
Intro to OurBigBook
. Source. We have two killer features:
- topics: topics group articles by different users with the same title, e.g. here is the topic for the "Fundamental Theorem of Calculus" ourbigbook.com/go/topic/fundamental-theorem-of-calculusArticles of different users are sorted by upvote within each article page. This feature is a bit like:
- a Wikipedia where each user can have their own version of each article
- a Q&A website like Stack Overflow, where multiple people can give their views on a given topic, and the best ones are sorted by upvote. Except you don't need to wait for someone to ask first, and any topic goes, no matter how narrow or broad
This feature makes it possible for readers to find better explanations of any topic created by other writers. And it allows writers to create an explanation in a place that readers might actually find it.Figure 1. Screenshot of the "Derivative" topic page. View it live at: ourbigbook.com/go/topic/derivativeVideo 2. OurBigBook Web topics demo. Source. - local editing: you can store all your personal knowledge base content locally in a plaintext markup format that can be edited locally and published either:This way you can be sure that even if OurBigBook.com were to go down one day (which we have no plans to do as it is quite cheap to host!), your content will still be perfectly readable as a static site.
- to OurBigBook.com to get awesome multi-user features like topics and likes
- as HTML files to a static website, which you can host yourself for free on many external providers like GitHub Pages, and remain in full control
Figure 2. You can publish local OurBigBook lightweight markup files to either OurBigBook.com or as a static website.Figure 3. Visual Studio Code extension installation.Figure 5. . You can also edit articles on the Web editor without installing anything locally. Video 3. Edit locally and publish demo. Source. This shows editing OurBigBook Markup and publishing it using the Visual Studio Code extension. - Infinitely deep tables of contents:
All our software is open source and hosted at: github.com/ourbigbook/ourbigbook
Further documentation can be found at: docs.ourbigbook.com
Feel free to reach our to us for any help or suggestions: docs.ourbigbook.com/#contact







