Salta al contenuto
Note per Studenti Foundations of Computer Science - Exam of 30 June 2021 Report

Foundations of Computer Science - Exam of 30 June 2021

Questa pagina non ha ancora la versione ripasso: qui sotto c'è il testo completo.

In questa pagina 3

Programming exam of the equivalent Italian-language course "Fondamenti di Informatica" (Engineering, University of Padova), 30 June 2021 (a.a. 2020-2021), translated into English. It is a practical test at the computer: the candidate writes Java code, which is compiled and run by the examiners. A program that does not compile is graded insufficient. The source does not state the duration or the points of each exercise, so none are invented here.

The source has two exercises. The text of Exercise 1 is the comment at the top of its starting file (VerificaOrdinamento.java); there is no separate PDF for it. The text of Exercise 2 is the exam sheet, with the given files Container.java, Dictionary.java, SIG.java and campioni.txt.

Exercise 2 uses constructs that the notes of this course do not explain in depth: interfaces, the Comparable interface, try/catch with exceptions and an inner class. Each one is explained in two lines the first time it appears. The code of both solutions was compiled and run with a JDK 21 (outputs below are the real ones).

Exercise 1 (points not stated in the source)

Check whether an array of integers is sorted in increasing order, in decreasing order, or not sorted.

Implement the following method:

java
public static int verificaOrdinamento(int[] array)

The method must check whether the content of the array is sorted "increasing", "decreasing", or not sorted. You may choose whether to implement the method with strictly increasing or strictly decreasing order, or not. The value returned by the method must be: 1 (= increasing), -1 (= decreasing) or 0 (= undefined).

It is not mandatory to use the toString method as implemented, although it could be useful. It may be modified anyway.

The starting file contains the constants CRESCENTE = 1, INDEFINITO = 0, DECRESCENTE = -1 and a main that calls the method on these four arrays:

java
{ 1, 42, 42 }   { 3, 5, 5, 8, 42 }   { 42, 9, 6 }   { 3, 5, 6, 4, 42 }
Show the result

The signature is public static int verificaOrdinamento(int[] array). With the non-strict version (equal neighbours allowed), the starting main must print:

{ 1, 42, 42 }  --->  1 (crescente)
{ 3, 5, 5, 8, 42 }  --->  1 (crescente)
{ 42, 9, 6 }  --->  -1 (decrescente)
{ 3, 5, 6, 4, 42 }  --->  0 (indefinito)

(The words in brackets are added by the starting prova method: "crescente" = increasing, "decrescente" = decreasing, "indefinito" = undefined.) With the strict version the first two lines would give 0 instead of 1, because of the repeated 42 and 5.

Show the full solution

Idea. An array is non-strictly increasing if no element is smaller than its predecessor, and non-strictly decreasing if no element is larger than its predecessor. One pass over the array is enough: two boolean flags start at true, and each pair of neighbours array[i-1], array[i] can only switch a flag to false.

  1. crescente = true, decrescente = true.
  2. For i from 1 to array.length - 1: if array[i] < array[i-1] the array cannot be increasing, so crescente = false; if array[i] > array[i-1] it cannot be decreasing, so decrescente = false.
  3. After the loop, return 1 if crescente, else -1 if decrescente, else 0.
java
public static int verificaOrdinamento(int[] array)
{
    boolean crescente = true;     // still compatible with increasing order
    boolean decrescente = true;   // still compatible with decreasing order

    for (int i = 1; i < array.length; i++)
    {
        if (array[i] < array[i - 1]) crescente = false;
        if (array[i] > array[i - 1]) decrescente = false;
    }

    if (crescente)   return CRESCENTE;    // 1
    if (decrescente) return DECRESCENTE;  // -1
    return INDEFINITO;                    // 0
}

Trace on { 3, 5, 6, 4, 42 }: pair (3,5): 5 > 3 so decrescente = false. Pair (5,6): same. Pair (6,4): 4 < 6 so crescente = false. Both flags are now false, so the result is 0. On { 42, 9, 6 }: (42,9) makes crescente false, (9,6) changes nothing, decrescente is still true, result -1.

Strict version. Use <= and >= in the two tests: array[i] <= array[i-1] makes crescente false, array[i] >= array[i-1] makes decrescente false.

Edge cases. For an array with 0 or 1 elements, or with all equal elements, the loop never turns a flag off, so both flags stay true and the method returns 1 (the if (crescente) comes first). This is a convention: the text does not say what to return. With the strict version, arrays of length 0 or 1 still return 1, while an array of equal elements of length 2 or more returns 0. If array could be null, a check at the start would be needed; the text does not require it.

Cost. One loop of n−1n-1 steps with constant work in each: 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 →. The array is only read, never changed. Arrays and length: 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 →.

Test run with the four given arrays plus { 7, 7, 7 }, { 5 }, { } and { 5, 3, 3, 1 }:

{ 1, 42, 42 }  --->  1
{ 3, 5, 5, 8, 42 }  --->  1
{ 42, 9, 6 }  --->  -1
{ 3, 5, 6, 4, 42 }  --->  0
{ 7, 7, 7 }  --->  1
{ 5 }  --->  1
{ }  --->  1
{ 5, 3, 3, 1 }  --->  -1

Exercise 2 (points not stated in the source)

Measures stored in a dictionary.

The attached interface Dictionary defines a dictionary, that is a container of key/value pairs:

java
import java.util.NoSuchElementException;

public interface Dictionary extends Container
{
   void insert(Comparable key, Object value);
   void remove(Comparable key) throws NoSuchElementException;
   Object find(Comparable key) throws NoSuchElementException;
}

where:

  • void insert(Comparable key, Object value): if the key does not exist, it adds the key/value pair to the dictionary; otherwise the value associated with it is overwritten with the new value;
  • void remove(Comparable key): if the key exists, it removes the key/value pair from the container;
  • Object find(Comparable key): searches by key and returns the value associated with it. If the key is not in the container, it throws the exception java.util.NoSuchElementException.

The interface Container is the following:

java
public interface Container
{
   void makeEmpty();
   boolean isEmpty();
   int size();
}

where:

  • void makeEmpty() makes the container empty;
  • boolean isEmpty() returns true if the container is empty, false otherwise;
  • int size() returns the number of pairs in the container.

The following class SIG (attached) implements the interface Dictionary, where, in particular:

  • toSortedKeyArray() returns an array, with size equal to the number of elements in the container, containing only the keys sorted in increasing order.

The candidate writes a test class Main that:

  • defines an instance of the class SIG;
  • reads the data of the pairs from a file, one pair per line. The data are floating-point numbers, as shown in the attached file campioni.txt. If a line does not contain at least two numbers, the message "riga n: java.util.NoSuchElementException" must be sent to standard error, where n is the line number. If one of the two numbers on the line is not in a correct format, the message "riga n: java.lang.NumberFormatException" must be sent to standard error, where n is the line number. The name of the file is passed as a command-line argument;
  • inserts the pairs into the container, writing to standard output the message "--> key/value", where key and value are the data of the pair;
  • calls the method toSortedKeyArray;
  • removes all pairs from the container, writing to standard output the message "<-- key/value", where key and value are the data of the pair.

At grading time the code will be tried with the commands:

rm *.class
javac *.java
java Main campioni.txt

(the printed sheet says javac Main campioni.txt, which is a misprint: the second command must be java). Tests that produce compilation errors are graded insufficient.

In writing the class Main it is not allowed to use classes of the standard library, except those of the packages java.lang and java.io and the classes java.util.Scanner and NoSuchElementException.

The file campioni.txt (note the second line, with a decimal comma, and the third, with one number only):

1.25 42.0
1,25 36.0
1.25
1.0  30.0
0.75 24.0
0.5  18.0
0.25 42.0
Show the result

Only Main.java has to be written; Container.java, Dictionary.java and SIG.java are given and are not changed. Required signature: public static void main(String[] args) throws IOException. With java Main campioni.txt the standard output is:

***LETTURA DATI DA FILE E INSERIMENTO ELEMENTI NEL DIZIONARIO***
--> 1.25/42.0
--> 1.0/30.0
--> 0.75/24.0
--> 0.5/18.0
--> 0.25/42.0

***RIMOZIONE ELEMENTI DAL DIZIONARIO***
<-- 0.25/42.0
<-- 0.5/18.0
<-- 0.75/24.0
<-- 1.0/30.0
<-- 1.25/42.0

and on standard error:

riga 2: java.lang.NumberFormatException: For input string: "1,25"
riga 3: java.util.NoSuchElementException

(The two headings are printed by the official solution; the text of the exam does not require them. The part after NumberFormatException is added by Java when the exception object is printed: it is acceptable, because the program prints the exception itself. Standard output and standard error are two separate streams: in the terminal they are interleaved, so the order of the lines on screen can differ.) Line 2 is wrong because of the decimal comma, line 3 has one number only, so neither is inserted. The pairs are removed in increasing order of key.

Show the full solution

Constructs used for the first time (two lines each).

  • Interface: a list of method signatures with no body (Container, Dictionary). A class that implements it must define all its methods, so any code written against the interface works with any implementation. interface Dictionary extends Container means: a Dictionary must also provide the methods of Container.
  • Comparable: an interface of the standard library with one method compareTo(x), that returns a negative number, zero or a positive number if the object is smaller than, equal to or larger than x. Double, Integer and String are Comparable. The keys of the dictionary are Comparable, so they can be kept in order. Object is the class of which every other class is a subclass, so the value can be anything (here a Double).
  • Exception: an object that is "thrown" when something goes wrong and interrupts the normal flow; a try { ... } catch (SomeException e) { ... } block runs the catch part if the try part throws that exception. NoSuchElementException and NumberFormatException are unchecked: the compiler does not force you to declare or catch them. IOException (file errors) is checked, so main declares throws IOException.
  • Inner class: Pair is declared inside SIG: it is a helper type that exists only for the dictionary.

1. The given classes, explained. SIG keeps the pairs in an array m of Pair objects, sorted by key, and a counter mSize of the pairs in use (the array can be longer than mSize).

Given code (as in the solution, only the comments translated):

java
// Container.java
public interface Container
{
   void makeEmpty();     // makes the container empty
   boolean isEmpty();    // true if the container is empty
   int size();           // number of elements in the container
}
java
// Dictionary.java
import java.util.NoSuchElementException;

public interface Dictionary extends Container
{
   void insert(Comparable key, Object value);                   // new key: add; existing key: overwrite the value
   void remove(Comparable key) throws NoSuchElementException;
   Object find(Comparable key) throws NoSuchElementException;
}
java
// SIG.java - dictionary on a sorted resizable array
import java.util.NoSuchElementException;

public class SIG implements Dictionary
{
   final static private int INITIAL_DIM = 1;

   private Pair[] m;          // pairs, sorted by key
   private int mSize = 0;     // number of pairs in use

   public SIG() { makeEmpty(); }

   public void makeEmpty()
   {
      m = new Pair[INITIAL_DIM];
      mSize = 0;
   }

   public boolean isEmpty() { return mSize == 0; }

   public int size() { return mSize; }

   // O(n)
   public void insert(Comparable key, Object value)
   {
      int indx = findPos(key);
      if (indx >= 0)                       // key already present: overwrite
      {
         m[indx] = new Pair(key, value);
         return;
      }

      if (mSize >= m.length)               // array full: double it
         resize();

      Pair tmp = new Pair(key, value);
      int j;
      for (j = mSize; j > 0 && tmp.compareTo(m[j - 1]) < 0; j--)
         m[j] = m[j - 1];                  // shift the larger pairs to the right
      m[j] = tmp;
      mSize++;
   }

   // O(n)
   public void remove(Comparable key)
   {
      int indx = findPos(key);
      if (indx >= 0)
      {
         for (int i = indx; i < mSize - 1; i++)
            m[i] = m[i + 1];               // shift to the left
         m[mSize - 1] = null;
         mSize--;
      }
   }

   // O(log n)
   public Object find(Comparable key) throws NoSuchElementException
   {
      int indx = findPos(key);
      if (indx < 0)
         throw new NoSuchElementException();
      return m[indx].value;
   }

   // O(n)
   public Comparable[] toSortedKeyArray()
   {
      Comparable[] a = new Comparable[mSize];
      for (int i = 0; i < mSize; i++)
         a[i] = m[i].key;
      return a;
   }

   // O(n)
   private void resize()
   {
      Pair[] a = new Pair[2 * m.length];
      for (int i = 0; i < m.length; i++)
         a[i] = m[i];
      m = a;
   }

   // O(log n)
   private int findPos(Comparable key)
   {
      Pair target = new Pair(key, null);
      return binSearch(m, 0, mSize - 1, target);
   }

   private int binSearch(Pair[] p, int from, int to, Pair t)
   {
      if (from > to)
         return -1;                        // not found

      int mid = (from + to) / 2;

      if (t.compareTo(p[mid]) == 0)
         return mid;
      if (t.compareTo(p[mid]) < 0)
         return binSearch(p, from, mid - 1, t);
      else
         return binSearch(p, mid + 1, to, t);
   }

   class Pair implements Comparable<Pair>
   {
      Comparable key;
      Object value;

      Pair(Comparable k, Object v) { key = k; value = v; }

      Pair() { this(0, 0); }

      public int compareTo(Pair p)         // pairs are compared by key only
      {
         return key.compareTo(p.key);
      }
   }
}

Two remarks on the given code. (a) Dictionary says that remove throws NoSuchElementException when the key is missing, but this remove silently does nothing: not a problem for Main, which only removes existing keys. (b) Pair() is never used.

2. The class Main, step by step.

  1. new SIG() creates the dictionary.
  2. new FileReader(args[0]) opens the file whose name is the first command-line argument (args[0]: "campioni.txt"; arguments are explained in 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 →). new Scanner(reader) lets us read it line by line with hasNextLine() and nextLine() (Scanner: 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 →).
  3. A counter n counts the lines, to write "riga n" in the messages.
  4. Each line is split into tokens by a second Scanner on the line string. tok.next() returns the next word, separated by any number of spaces (so 1.0 30.0 with two spaces works), and throws NoSuchElementException if there is none.
  5. Inside try, the first token is converted to a Double for the key, the second for the value: Double.valueOf(String) throws NumberFormatException if the text is not a number. "1,25" is rejected because the decimal separator in Java is the point. The old form new Double(String) also works but is deprecated: both are in java.lang, so allowed.
  6. The pair is inserted and "--> key/value" is printed after insert, inside the try: so a line that fails on the second number (line 3: 1.25 has no value) prints nothing and inserts nothing, because the exception interrupts the block before s.insert.
  7. Two catch blocks write the required messages to System.err. Printing the exception object e with + e gives java.util.NoSuchElementException or java.lang.NumberFormatException: For input string: "1,25".
  8. After the loop, toSortedKeyArray() returns the keys in increasing order. While the dictionary is not empty, take the next key, read its value with find, delete the pair with remove and print "<-- key/value". The value must be read before remove, otherwise find would throw.
java
// Main.java
import java.io.FileReader;
import java.io.IOException;

import java.util.Scanner;
import java.util.NoSuchElementException;

public class Main
{
   public static void main(String[] args) throws IOException
   {
      SIG s = new SIG();                               // the dictionary

      FileReader r = new FileReader(args[0]);          // file name from the command line
      Scanner in = new Scanner(r);

      System.out.println("***LETTURA DATI DA FILE E INSERIMENTO ELEMENTI NEL DIZIONARIO***");
      int n = 0;                                       // line number
      while (in.hasNextLine())
      {
         String line = in.nextLine();
         n++;
         Scanner tok = new Scanner(line);              // splits the line into words
         try {
            Comparable key = Double.valueOf(tok.next());   // may throw NoSuchElementException / NumberFormatException
            Object value = Double.valueOf(tok.next());
            s.insert(key, value);
            System.out.println("--> " + key + "/" + value);
         }
         catch (NoSuchElementException e)              // fewer than two numbers on the line
         {
            System.err.println("riga " + n + ": " + e);
         }
         catch (NumberFormatException e)               // a token is not a valid number
         {
            System.err.println("riga " + n + ": " + e);
         }
      }

      System.out.println();
      System.out.println("***RIMOZIONE ELEMENTI DAL DIZIONARIO***");
      Comparable[] a = s.toSortedKeyArray();           // keys in increasing order

      int i = 0;
      while (!s.isEmpty())
      {
         Comparable key = a[i++];
         Object value = s.find(key);                   // read the value BEFORE removing the pair
         s.remove(key);
         System.out.println("<-- " + key + "/" + value);
      }
   }
}

3. Trace on campioni.txt. The array m grows 1, 2, 4, 8 as pairs arrive.

  • Line 1 1.25 42.0: dictionary empty, m = [1.25].
  • Line 2 1,25 36.0: Double.valueOf("1,25") throws, message on System.err, nothing inserted.
  • Line 3 1.25: the first next() gives the key; the second throws NoSuchElementException; nothing inserted.
  • Line 4 1.0 30.0: m = [1.0, 1.25]: 1.25 was shifted one place right.
  • Line 5 0.75 24.0: m = [0.75, 1.0, 1.25]. Line 6: [0.5, 0.75, 1.0, 1.25]. Line 7: [0.25, 0.5, 0.75, 1.0, 1.25].
  • toSortedKeyArray() returns those five keys; the loop prints them in this order, each time removing the first pair of m, until isEmpty() is true.

Two more checks, with a file 2.0 1.0 / 1.0 5.0 / 2.0 9.0 / abc 3 / (empty line) / 3.0 4.0 7: the third line overwrites the value of key 2.0 (the removal phase prints <-- 2.0/9.0, only one pair for that key); abc 3 gives NumberFormatException (line 4); the empty line gives NoSuchElementException (line 5); 3.0 4.0 7 is accepted, the third token is ignored. The output is --> 2.0/1.0, --> 1.0/5.0, --> 2.0/9.0, --> 3.0/4.0 and then <-- 1.0/5.0, <-- 2.0/9.0, <-- 3.0/4.0.

Typical mistakes.

  • Using Scanner on the whole file and nextDouble(): a bad line then stops the whole reading and the line numbers are lost. Read a line, then split it.
  • Printing "--> ..." before insert or outside the try: a bad line would print a pair.
  • Removing the pair before reading its value, or using s.size() as the number of keys while removing (it changes during the loop): the array a is the fixed list of keys.
  • Using a class outside the allowed ones (for example ArrayList or Arrays.sort): forbidden by the text.
  • Forgetting throws IOException on main: compile error, and a program that does not compile is graded insufficient.
  • Writing System.out instead of System.err for the two error messages.

Test code and files were run from a directory with Container.java, Dictionary.java, SIG.java, Main.java and campioni.txt (javac *.java, then java Main campioni.txt); the compiler only prints a note about unchecked operations in SIG.java (raw Comparable), no error.

Self-assessment grid
Exercise Points What must be there for full points Typical mistakes
1 not stated verificaOrdinamento returns 1, -1 or 0 exactly as required, on the four sample arrays; one pass with two flags (or equivalent); the choice strict/non-strict is consistent with the tests < and <= mixed up, so { 1, 42, 42 } gives the wrong value; returning after the first pair without scanning the whole array; going out of bounds with i = 0 and array[i-1]; changing the constants
2 - reading not stated file name taken from args[0]; one Scanner per line; line counter; two numbers read as Double; the two messages on System.err with the right line number nextDouble() on the whole file; wrong line number (counting from 0, or counting only good lines); messages on System.out; missing throws IOException
2 - insertion not stated pair inserted with s.insert, "--> key/value" printed only for valid lines; line 3 of the sample file inserts nothing printing before the exception can occur; inserting the key when the value is missing
2 - removal not stated toSortedKeyArray() called; loop until isEmpty(); find before remove; "<-- key/value" in increasing key order removing first and then calling find (exception); wrong loop condition; using a forbidden library class; code that does not compile with javac *.java