Foundations of Computer Science - Exam of 13 February 2018
Questa pagina non ha ancora la versione ripasso: qui sotto c'è il testo completo.
In questa pagina 3
Practical programming test of the Italian-language equivalent of Foundations of Computer Science (Fondamenti di Informatica, Engineering, University of Padova), translated into English. The test is done at the computer in Java: the text gives the file CD.java (the interface), the candidate writes the other three files and leaves them in the home folder. The text states no points: a test whose files do not compile is judged insufficient. The code below was compiled with JDK 21 and run on the sample input and on random tests (see the end of the Solution of Exercise 2).
Constructs not explained in the notes of this course (they appear in the text, each is explained here the first time): interface and implements, the throws clause, a user-defined exception (extends RuntimeException), the amortized analysis of an operation, and, in the alternative solution, a class declared inside another class and a chain of linked cells.
Exercise 1 (points not stated)
The abstract data type CD (double-ended queue) is defined by the following Java interface:
public interface CD
{ int size();
boolean isEmpty();
void addFirst (Object x); // adds at the beginning of the queue
void addLast (Object x); // adds at the end of the queue
Object removeFirst () throws EmptyCDException; // removes from the beginning
Object removeLast () throws EmptyCDException; // removes from the end
Object getFirst () throws EmptyCDException; // element at the beginning
Object getLast () throws EmptyCDException; // element at the end
}Write the class MiaCD that implements the interface CD so that all the primitives take time , or time in terms of amortized analysis, and the exception handler EmptyCDException that extends RuntimeException.
Show the result
Two files, EmptyCDException.java and MiaCD.java, that compile together with CD.java.
EmptyCDException: a class thatextends RuntimeException, with two constructors (with and without message).MiaCD implements CD, with the eight methods of the interface:
| method | behaviour | cost |
|---|---|---|
size() |
number of elements | |
isEmpty() |
true if there are no elements |
|
addFirst(x), addLast(x) |
insert x at the beginning / at the end |
amortized (array) |
removeFirst(), removeLast() |
remove and return the first / last element; EmptyCDException if the queue is empty |
|
getFirst(), getLast() |
return without removing; EmptyCDException if empty |
Show the full solution
Step 0: the new constructs.
- An interface is a list of method signatures without bodies: it says what a type can do, not how. A class that
implements CDpromises to define all of them (the compiler checks), and a variable of typeCDcan then refer to any such class. throws EmptyCDExceptionin a signature declares that the method may end by throwing that exception. Throwing meansthrow new EmptyCDException();: the method stops at once and the exception goes to the caller.- An exception class is an ordinary class that
extendsa standard one. By extendingRuntimeExceptionthe exception is unchecked: callers are not obliged to catch it or to writethrows, soMaincan callremoveFirst()withouttry/catch. If nobody catches it, the program stops with an error message. Objectis the root of all classes: a variable of typeObjectcan hold a reference to any object (here the strings read byMain).
Step 1: the exception. It needs only two constructors that pass the message to the superclass (super(...) calls the constructor of RuntimeException):
// EmptyCDException.java -- thrown when we read from an empty double-ended queue
public class EmptyCDException extends RuntimeException
{ public EmptyCDException (String message) { super(message); }
public EmptyCDException () { super(); }
}Step 2: choosing the data structure. The four operations at the two ends in constant time exclude a plain array in which the elements start at index 0 (inserting at the beginning would shift everything: , see Computational ComplexityAlgorithms are analysed to predict performance on unseen inputs and to compare solutions of the same problem, mainly in time (also in space). Experimental analysis times an implementation (time.time(), doubling input sizes, T(n) = an^b with b = log2(T(2n)/T(n))) but measures the implementation, not the algorithm. Theoretical analysis counts basic steps under a cost model and classifies the result with asymptotic notation: O is an upper bound, Omega a lower bound, Theta both (f(n) <= cg(n) for all n >= n0). Rules: sum sequential blocks, take the larger branch of an if for an upper bound (the smaller for a lower bound), sum the iterations of a loop. Worked case: reverse a list with a shifting inner loop is Theta(n^2); writing each element directly in its place is Theta(n), and no faster hardware can compensate for the worse class on large inputs.Computational Complexity →). Two good choices:
- a circular array (Java - ArraysA Java array is an object holding a sequence of elements of the same type (primitive or reference). It is built with new TypeName[length], assigned to a reference variable declared TypeName[] name (no length in the declaration, so the variable can later refer to arrays of any length). Elements start at 0, false or null; they are read and written with name[index], with index from 0 to length - 1; any other index throws ArrayIndexOutOfBoundsException at run time (typical bug: index equal to length, or i <= values.length in a loop). The size is the public final variable length (not a method, cannot be assigned). Elements can be given at once with {2, 3, 5}. Assigning an array variable to another copies only the reference (both see the same array); a real copy needs a new array of the same type and length filled by a loop or by System.arraycopy(from, fromStart, to, toStart, count).Java - Arrays →) that doubles when it is full: all operations are except the doubling, which is on average (amortized). This is the main solution;
- a doubly linked chain with two sentinel cells: all operations are exactly (alternative, below).
Step 3: the circular array. The elements occupy consecutive cells of the array v, but the sequence can "wrap around": after the last cell v[v.length - 1] we continue from v[0] (and before v[0] we continue from the last cell). Three variables describe the state:
taglia: the number of elements;primo: the index of the cell just before the first element (the next free cell on the left);ultimo: the index of the cell just after the last element (the next free cell on the right).
So the first element is at primo + 1 and the last one at ultimo - 1, always understood modulo v.length: when an index goes out of the array it is brought back with if (i == v.length) i = 0; (or if (i == -1) i = v.length - 1;).
addLast(x): write inv[ultimo], then advanceultimo.addFirst(x): write inv[primo], then moveprimoback.removeFirst(): advanceprimo, and the element is inv[primo].removeLast(): moveultimoback, and the element is inv[ultimo].
The first element added to an empty queue is a special case: it is written in v[0] and primo, ultimo are set around it (primo = v.length - 1, ultimo = 1), whichever end it was added from.
Step 4: doubling. When taglia == v.length the array is full. raddoppia() creates an array of twice the length, copies the elements in order to its beginning (starting from primo + 1, with the wrap-around) and sets primo = tmp.length - 1 (the cell before index 0) and ultimo = taglia.
// MiaCD.java -- double-ended queue on a circular array that doubles when full
public class MiaCD implements CD
{ private Object[] v = new Object[1]; // the circular array
private int primo; // index of the cell just BEFORE the first element
private int ultimo; // index of the cell just AFTER the last element
private int taglia; // number of elements
public int size () { return taglia; }
public boolean isEmpty () { return taglia == 0; }
// double the array: copy the elements, in order, to the beginning of the new one
private void raddoppia ()
{ Object[] tmp = new Object[v.length * 2];
for (int i = 0; i < taglia; i++)
{ primo++;
if (primo == v.length) primo = 0; // wrap around
tmp[i] = v[primo];
}
primo = tmp.length - 1; // cell before index 0 (circularly)
ultimo = taglia; // cell after the last copied element
v = tmp;
}
public void addFirst (Object x)
{ if (taglia == v.length) raddoppia();
if (taglia == 0)
{ v[0] = x; primo = v.length - 1; ultimo = 1; }
else
{ v[primo] = x; primo--; if (primo == -1) primo = v.length - 1; }
taglia++;
}
public void addLast (Object x)
{ if (taglia == v.length) raddoppia();
if (taglia == 0)
{ v[0] = x; primo = v.length - 1; ultimo = 1; }
else
{ v[ultimo] = x; ultimo++; if (ultimo == v.length) ultimo = 0; }
taglia++;
}
public Object removeFirst () throws EmptyCDException
{ if (isEmpty()) throw new EmptyCDException("empty queue");
taglia--;
primo++;
if (primo == v.length) primo = 0;
return v[primo];
}
public Object removeLast () throws EmptyCDException
{ if (isEmpty()) throw new EmptyCDException("empty queue");
taglia--;
ultimo--;
if (ultimo == -1) ultimo = v.length - 1;
return v[ultimo];
}
public Object getFirst () throws EmptyCDException
{ if (isEmpty()) throw new EmptyCDException("empty queue");
int p = primo + 1;
if (p == v.length) p = 0;
return v[p];
}
public Object getLast () throws EmptyCDException
{ if (isEmpty()) throw new EmptyCDException("empty queue");
int u = ultimo - 1;
if (u == -1) u = v.length - 1;
return v[u];
}
}Notes on the code:
- The test
isEmpty()comes before any change oftaglia,primo,ultimo: an exception must leave the queue untouched. - In
getFirst/getLastthe local variablespanduare used instead of changingprimo/ultimo: reading must not modify the state. - Removed elements stay in the array (the cell is simply considered free): not wrong, only memory that is released at the next overwrite.
- In
addFirst/addLastthe doubling is checked before inserting, so there is always a free cell.
Trace. Three addLast("A"), addLast("B"), addLast("C") on a new queue (v has length 1):
| operation | what happens | v |
primo |
ultimo |
taglia |
|---|---|---|---|---|---|
addLast("A") |
empty: special case | [A] |
0 | 1 | 1 |
addLast("B") |
full: doubling copies A, then v[ultimo = 1] = B, ultimo goes to 2, wraps to 0 |
[A, B] |
1 | 0 | 2 |
addLast("C") |
full: doubling to length 4 copies A, B; primo = 3, ultimo = 2; then v[2] = C |
[A, B, C, _] |
3 | 3 | 3 |
Now getFirst() reads v[primo + 1], that is v[4], wrapped to v[0] = A; getLast() reads v[ultimo - 1] = v[2] = C. Correct. Then removeLast() gives C (ultimo goes back to 2), and addFirst("Z") writes v[primo = 3] = Z and primo becomes 2: the sequence is now Z, A, B and it wraps around the end of the array.
Why the cost is amortized. Every operation except the doubling does a fixed number of steps: . The doubling of an array of length costs (copy of elements). Starting from length 1 and doing insertions, the doublings happen at lengths up to less than , and their total cost is at most . So insertions cost in total, that is for each insertion on average over the whole sequence: this is the amortized cost. A single insertion can cost , but only rarely. (If the array grew by a fixed amount, say 10 cells, the total would be : doubling is what makes it work.)
Alternative solution: doubly linked chain. Every element lives in a cell with a reference to the left and to the right cell. Two sentinel cells testa (head) and coda (tail) never hold data: they remove all special cases (empty chain, one element), because every real cell always has a left and a right neighbour. Cella is declared inside MiaCD and private, so nobody else can see it. Here all operations are in the strict sense, and nothing is copied.
// MiaCD.java -- double-ended queue on a doubly linked chain with two sentinel cells
public class MiaCD implements CD
{ private class Cella
{ Object el; // element stored in the cell
Cella s, d; // left (previous) and right (next) cell
Cella (Object x, Cella y, Cella z) { el = x; s = y; d = z; }
}
private int taglia;
private Cella testa, coda; // sentinels: they never hold data
public MiaCD ()
{ testa = new Cella(null, null, null);
coda = new Cella(null, testa, null);
testa.d = coda;
}
public int size () { return taglia; }
public boolean isEmpty () { return taglia == 0; }
public void addFirst (Object x)
{ testa.d = new Cella(x, testa, testa.d); // new cell between testa and the old first
testa.d.d.s = testa.d; // the old first points back to the new cell
taglia++;
}
public void addLast (Object x)
{ coda.s = new Cella(x, coda.s, coda); // new cell between the old last and coda
coda.s.s.d = coda.s; // the old last points forward to the new cell
taglia++;
}
public Object removeFirst () throws EmptyCDException
{ if (isEmpty()) throw new EmptyCDException("empty queue");
taglia--;
Object tmp = testa.d.el;
testa.d = testa.d.d; // skip the first cell
testa.d.s = testa;
return tmp;
}
public Object removeLast () throws EmptyCDException
{ if (isEmpty()) throw new EmptyCDException("empty queue");
taglia--;
Object tmp = coda.s.el;
coda.s = coda.s.s; // skip the last cell
coda.s.d = coda;
return tmp;
}
public Object getFirst () throws EmptyCDException
{ if (isEmpty()) throw new EmptyCDException("empty queue");
return testa.d.el;
}
public Object getLast () throws EmptyCDException
{ if (isEmpty()) throw new EmptyCDException("empty queue");
return coda.s.el;
}
}The constructor Cella(x, y, z) sets the element, the left and the right neighbour of the new cell; the two other pointers (the neighbours that must point to the new cell) are fixed by the second line of addFirst/addLast. The array solution is shorter to reason about with the notes of this course (Java - ArraysA Java array is an object holding a sequence of elements of the same type (primitive or reference). It is built with new TypeName[length], assigned to a reference variable declared TypeName[] name (no length in the declaration, so the variable can later refer to arrays of any length). Elements start at 0, false or null; they are read and written with name[index], with index from 0 to length - 1; any other index throws ArrayIndexOutOfBoundsException at run time (typical bug: index equal to length, or i <= values.length in a loop). The size is the public final variable length (not a method, cannot be assigned). Elements can be given at once with {2, 3, 5}. Assigning an array variable to another copies only the reference (both see the same array); a real copy needs a new array of the same type and length filled by a loop or by System.arraycopy(from, fromStart, to, toStart, count).Java - Arrays →); the chain is the classical textbook answer: both are accepted.
Exercise 2 (points not stated)
Write a test class Main.java that:
- creates three instances of the class
MiaCD, calleduno,dueandtre; - reads from the standard input a sequence of strings (one per line) and inserts them at the end of the queue
uno; then empties the queueunofrom the end (withremoveLast), moving its content to the beginning of the queuedue; then empties the queueduefrom the beginning (withremoveFirst), inserting the data at the end of the queuetre; finally empties the queuetrefrom the beginning, writing the data on the standard output, one per line. The output data must therefore be in the same order as the input data.
The submitted work is tested with the following commands:
rm MiaCD.class; rm Main.class; rm EmptyCDException.class
javac *.java
java Main <stringhe.txt >output.txt
diff stringhe.txt output.txt # and the two files must be equalShow the result
Main.java compiles with the three other files, and java Main <stringhe.txt >output.txt gives an output.txt equal to the input, line by line. With the input
Hello
world!
Ciao
mondo!the output is the same four lines in the same order. The data go through the three queues as: uno = Hello, world!, Ciao, mondo!; due = same order (each removeLast of uno is an addFirst in due: the reversal of a reversal); tre = same order.
Show the full solution
Step 1: read. Java - Classes, Objects and ScannerIn Java a class defines instance variables (usually private), a constructor and methods; objects are created with new and used through reference variables. A method call p1.getDistanceFrom(p2) has an implicit argument (the object p1, available inside the method as this) and explicit arguments (p2). Arguments are always passed by value: a copy of the value or of the reference is passed. Comparing references with == tests whether they point to the same object, while equals() compares the content; null is tested with ==; floating point numbers are compared with a tolerance. Public methods are documented with javadoc comments (param, return). The Scanner class splits a string or the standard input into tokens with hasNext() and next() and offers hasNextInt, hasNextDouble, hasNextLine; the end of the standard input is ctrl+z then return on Windows and ctrl+d on Unix. Worked exercises: the MyPoint2D point class with its tester, and the specification of a MyComplex class.Java - Classes, Objects and Scanner → shows how to read a sequence from the standard input: a Scanner on System.in and a loop while (in.hasNextLine()) with in.nextLine(). Every line is added at the end of uno, so uno contains the lines in input order, first line at the beginning.
Step 2: first transfer. removeLast on uno gives the lines from the last to the first; each one is put at the beginning of due with addFirst. The last line is inserted first, then the one before it in front of it, and so on: the first line ends up in front. So due has the original order again (two reversals cancel).
Step 3: second transfer. removeFirst on due gives the lines in order; addLast on tre keeps that order.
Step 4: print. removeFirst on tre gives the lines in order, written with System.out.println.
// Main.java -- test of MiaCD: the input order is preserved
import java.util.Scanner;
public class Main
{ public static void main (String[] arg)
{ Scanner in = new Scanner(System.in);
MiaCD uno = new MiaCD();
MiaCD due = new MiaCD();
MiaCD tre = new MiaCD();
while (in.hasNextLine()) // 1. read the lines, append to "uno"
uno.addLast(in.nextLine());
while (!uno.isEmpty()) // 2. empty "uno" from the end, push to the front of "due"
due.addFirst(uno.removeLast());
while (!due.isEmpty()) // 3. empty "due" from the front, append to "tre"
tre.addLast(due.removeFirst());
while (!tre.isEmpty()) // 4. empty "tre" from the front, print
System.out.println(tre.removeFirst());
if (!uno.isEmpty() || !due.isEmpty() || !tre.isEmpty())
System.err.println("Error"); // sanity check: all queues must be empty
}
}Notes:
- The loops stop with
isEmpty(), soremoveFirst/removeLastare never called on an empty queue andEmptyCDExceptionis never thrown. System.out.println(tre.removeFirst())accepts anObjectand prints its text: here the string. The queue storesObject, so no cast is needed to print or to move the elements; a cast(String)would be needed only to callStringmethods.hasNextLine()is preferred tohasNext(): it also handles empty lines in the input, which are real (empty) lines to reproduce. With the redirection<stringhe.txtthe standard input is the file (Java - MyComplex, Methods and RedirectionFull MyComplex class (complex numbers): private re and im, constructors chained with this(...) as first statement, methods add, sub, mult, div (= mult by inv), inv, conj, mod, re, im, toString, equalsApprox with a private static helper using a relative tolerance 1E-14. Style rules: give constructor arguments names different from the instance variables (or use this.re = re), never overwrite method arguments, avoid the stray semicolon after if/for/while. Concepts: accessor vs modifier methods (immutable classes only have accessors, e.g. MyComplex and String), boolean methods, formal vs actual arguments, Java passes everything by value (a copy of the number or of the reference), so a method can change the state of an object it receives but cannot make the caller's variable refer to another object; instance methods use this and instance variables, static methods only their explicit arguments; private methods can be called only inside the class. Finally standard input/output redirection with < > >> from the terminal.Java - MyComplex, Methods and Redirection →).- No
throws IOExceptionis needed:Scannerdoes not throw checked exceptions. - On Linux (the exam machines)
diffcompares exactly; the sample file has no newline after its last line, sodiffmay report "No newline at end of file", which is only a difference in the last end-of-line, not in the data.
Verification (done with JDK 21). Both solutions (array and chain) were compiled with javac *.java and run with the sample input of the exam (12 lines): output.txt equals stringhe.txt line by line. A test with lines gave the same result for the array solution (about 2 seconds in total, consistent with the linear cost: each line is moved a constant number of times). A random test of 200 sequences of 2000 operations each (addFirst, addLast, removeFirst, removeLast, getFirst, getLast, also on empty queues) compared MiaCD with java.util.ArrayDeque for both solutions: same elements, same sizes, and EmptyCDException thrown exactly when the queue is empty. The text of the exercise is the 2017-2018 original; the solution code is the official one, with comments translated and small simplifications (hasNextLine, no redundant assignments in the chain).
Self-assessment grid
| exercise | points | what must be there for full points | typical mistakes |
|---|---|---|---|
1 - EmptyCDException |
not stated | class extends RuntimeException, constructors with and without message |
extending Exception (then every caller needs throws/try); forgetting the constructors |
1 - MiaCD |
not stated | implements CD with all 8 methods (the file compiles); constant time (array: doubling, never "grow by 1"); circular indices handled at both ends; EmptyCDException thrown on remove/get of an empty queue before changing any variable; correct isEmpty/size |
v.length instead of taglia for the size; an array that shifts the elements at every addFirst (); a doubling that copies the array without un-wrapping it (order lost); forgetting the special case of the first insertion; modifying primo/ultimo in getFirst/getLast; a method of the interface not implemented or not public (compile error) |
2 - Main |
not stated | three queues; the four loops in the right order and direction (addLast, then removeLast into addFirst, then removeFirst into addLast, then removeFirst printed); output equal to input |
using removeFirst in step 2 (the output comes out reversed); while (!uno.isEmpty()) replaced by a fixed count; printing with print instead of println; reading with next() (splits at spaces instead of lines); not handling the end of the input |
| whole test | not stated | the three files compile together with CD.java and diff gives no difference |
compile errors (judged insufficient); header with name, student number, workstation and date not filled in |