Salta al contenuto
Note per Studenti Foundations of Computer Science - Exam of 13 February 2018 Report

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:

java
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 O(1)O(1), or time O(1)O(1) 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 that extends 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 O(1)O(1)
isEmpty() true if there are no elements O(1)O(1)
addFirst(x), addLast(x) insert x at the beginning / at the end O(1)O(1) amortized (array)
removeFirst(), removeLast() remove and return the first / last element; EmptyCDException if the queue is empty O(1)O(1)
getFirst(), getLast() return without removing; EmptyCDException if empty O(1)O(1)
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 CD promises to define all of them (the compiler checks), and a variable of type CD can then refer to any such class.
  • throws EmptyCDException in a signature declares that the method may end by throwing that exception. Throwing means throw new EmptyCDException();: the method stops at once and the exception goes to the caller.
  • An exception class is an ordinary class that extends a standard one. By extending RuntimeException the exception is unchecked: callers are not obliged to catch it or to write throws, so Main can call removeFirst() without try/catch. If nobody catches it, the program stops with an error message.
  • Object is the root of all classes: a variable of type Object can hold a reference to any object (here the strings read by Main).

Step 1: the exception. It needs only two constructors that pass the message to the superclass (super(...) calls the constructor of RuntimeException):

java
// 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: O(n)O(n), 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:

  1. 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 O(1)O(1) except the doubling, which is O(1)O(1) on average (amortized). This is the main solution;
  2. a doubly linked chain with two sentinel cells: all operations are exactly O(1)O(1) (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 in v[ultimo], then advance ultimo.
  • addFirst(x): write in v[primo], then move primo back.
  • removeFirst(): advance primo, and the element is in v[primo].
  • removeLast(): move ultimo back, and the element is in v[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.

java
// 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 of taglia, primo, ultimo: an exception must leave the queue untouched.
  • In getFirst/getLast the local variables p and u are used instead of changing primo/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/addLast the 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 O(1)O(1) amortized. Every operation except the doubling does a fixed number of steps: O(1)O(1). The doubling of an array of length mm costs O(m)O(m) (copy of mm elements). Starting from length 1 and doing nn insertions, the doublings happen at lengths 1,2,4,…1, 2, 4, \dots up to less than nn, and their total cost is at most 1+2+4+⋯+n/2<n1 + 2 + 4 + \dots + n/2 < n. So nn insertions cost O(n)O(n) in total, that is O(1)O(1) for each insertion on average over the whole sequence: this is the amortized cost. A single insertion can cost O(n)O(n), but only rarely. (If the array grew by a fixed amount, say 10 cells, the total would be O(n2)O(n^2): 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 O(1)O(1) in the strict sense, and nothing is copied.

java
// 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, called uno, due and tre;
  • 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 queue uno from the end (with removeLast), moving its content to the beginning of the queue due; then empties the queue due from the beginning (with removeFirst), inserting the data at the end of the queue tre; finally empties the queue tre from 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 equal
Show 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.

java
// 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:

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 10610^6 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 (O(n)O(n)); 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