Salta al contenuto
Note per Studenti Foundations of Computer Science - Mock Exam 1 Report

Foundations of Computer Science - Mock Exam 1

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

In questa pagina 4

Mock exam built on the model of the written tests of the equivalent course in Italian (Fondamenti di Informatica, Information Engineering, UniPD), which mix short theory questions with Java programming problems. It is a proposal, not an official paper: the problems are written with our own words and data. Duration: 2 hours. Total: 30 points (Exercise 1: 8, Exercise 2: 10, Exercise 3: 12). No material allowed; code is written by hand, without compiler. Java problems give the method signature, the constraints on the input, examples and the required complexity.

Exercise 1 (points 8)

Eight short questions, 1 point each. Give the answer without a long justification, but keep your working.

  1. Write 20510205_{10} in binary and in hexadecimal.
  2. Write −4510-45_{10} in 8-bit two's complement, in binary and in hexadecimal.
  3. The 8-bit pattern 1010 0111 is read first as an unsigned integer and then as a two's complement integer. Give the two decimal values.
  4. Two 8-bit two's complement numbers 0x5A and 0x32 are added. Give the 8-bit result, the decimal value it represents and say whether there is overflow.
  5. Write −6.75-6.75 in IEEE 754 single precision (1 bit of sign, 8 bits of exponent in excess 127, 23 bits of fraction). Give the 32 bits as 8 hexadecimal digits.
  6. Which decimal number is represented by the IEEE 754 single precision pattern 0x42F60000?
  7. A computer executes 10910^9 elementary steps per second. An algorithm is run on an input of size n=106n=10^6. How long does it take if it performs about nn steps, about nlog⁡2nn\log_2 n steps, about n2n^2 steps? (Use log⁡2106≈20\log_2 10^6\approx 20 and give the order of magnitude: milliseconds, seconds, minutes...)
  8. A program takes 0.8 s on an input of size 4000 and 3.2 s on an input of size 8000. Assuming T(n)=a nbT(n)=a\,n^b, find bb and predict the time on size 32000.
Show the result
  1. 110011012=0xCD11001101_2 = \texttt{0xCD}.
  2. 1101 0011 =0xD3=\texttt{0xD3}.
  3. 167167 (unsigned) and −89-89 (two's complement).
  4. Result 1000 1100, which represents −116-116: overflow (90+50=14090+50=140 is above 127127).
  5. 0xC0D80000.
  6. 123123.
  7. nn steps: 10610^6 steps =1=1 ms. nlog⁡2nn\log_2 n: about 2⋅1072\cdot10^7 steps =20=20 ms. n2n^2: 101210^{12} steps =1000=1000 s, about 17 minutes.
  8. b=2b=2; T(32000)=51.2T(32000)=51.2 s.
Show the full solution

Theory: Representation of InformationEverything in a computer is a sequence of bits, so each kind of information needs a coding. Natural numbers use positional notation in base 2 (conversion by repeated division by 2); signed integers use two's complement (range from minus 2 to the n minus 1 up to 2 to the n minus 1, minus 1), where negation is invert-all-bits-and-add-1, sums are plain binary sums and overflow is detected on the two top carries; hexadecimal groups bits in fours; fractions use fixed point or IEEE 754 floating point (sign, exponent in excess 127, 23-bit fraction) and are only approximate; characters are unsigned integers in a code table (ASCII, Unicode); images, video and sound are stored as numbers too (pixels, frame differences, samples).Representation of Information → and 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 →.

1. Divide by 2 and read the remainders from the last to the first: 205→102205\to102 r1, →51\to51 r0, →25\to25 r1, →12\to12 r1, →6\to6 r0, →3\to3 r0, →1\to1 r1, →0\to0 r1. Reading upwards: 11001101. Check: 128+64+8+4+1=205128+64+8+4+1=205. Groups of four from the right: 1100 =C=\texttt{C}, 1101 =D=\texttt{D}, so 0xCD\texttt{0xCD}.

2. First 45=32+8+4+1=0010 1101245=32+8+4+1=0010\,1101_2. Then change the sign: invert every bit, 1101 0010, and add 1, 1101 0011. Check: −128+64+16+2+1=−45-128+64+16+2+1=-45. In hexadecimal 1101=D, 0011=3, so 0xD3. Common error: inverting without adding 1 gives 1101 0010 =−46=-46.

3. Unsigned: 128+32+4+2+1=167128+32+4+2+1=167. Two's complement: the leftmost bit weighs −128-128, so −128+32+4+2+1=−89-128+32+4+2+1=-89 (same as 167−256167-256). The same bits give different values: the format must be known.

4.

  0101 1010   (0x5A =  90)
+ 0011 0010   (0x32 =  50)
-----------
  1000 1100   (0x8C)

The leftmost bit is 1, so as two's complement the result is −128+8+4=−116-128+8+4=-116. The correct sum 140140 is outside the range [−128,127][-128,127]: overflow. It is detected also from the carries: there is a carry into the leftmost column (coming from the next bit) but none out of it, so exactly one of the two carries at the top is present. Two positive numbers gave a negative result: always a sign of overflow.

5. 6.75=110.112=1.10112⋅226.75=110.11_2=1.1011_2\cdot 2^2. The sign bit is 1 (negative). The stored exponent is 2+127=129=1000 000122+127=129=1000\,0001_2. The fraction is the part after the leading 1 (which is not stored): 1011 followed by 19 zeros. The 32 bits are 1 10000001 10110000000000000000000. Regroup in fours: 1100 0000 1101 1000 0000 0000 0000 0000 =0xC0D80000=\texttt{0xC0D80000}.

6. 0x42F60000 == 0100 0010 1111 0110 0000 .... Sign: 0, positive. Exponent bits: 1000 0101 =133=133, real exponent 133−127=6133-127=6. Fraction: 111 0110 0..., so the number is 1.1110112⋅26=11110112=64+32+16+8+2+1=1231.111011_2\cdot2^6=1111011_2=64+32+16+8+2+1=123.

7. At 10910^9 steps per second one step lasts 11 ns.

  • n=106n=10^6 steps: 106⋅10−910^6\cdot10^{-9} s =1=1 ms.
  • nlog⁡2n≈106⋅20=2⋅107n\log_2 n\approx 10^6\cdot 20=2\cdot10^7 steps: 2020 ms.
  • n2=1012n^2=10^{12} steps: 1012⋅10−9=100010^{12}\cdot10^{-9}=1000 s, about 17 minutes.

The nlog⁡nn\log n algorithm is only about 20 times slower than the linear one, while the quadratic one is a million times slower than the linear one: a quadratic algorithm is unusable already for a million items, while nlog⁡nn\log n is still instantaneous.

8. The constant aa cancels in the ratio: T(2n)T(n)=2b\dfrac{T(2n)}{T(n)}=2^b, so b=log⁡23.20.8=log⁡24=2b=\log_2\dfrac{3.2}{0.8}=\log_2 4=2 (quadratic, doubling the input multiplies the time by 4). Then a=0.8/40002=5⋅10−8a=0.8/4000^2=5\cdot10^{-8} and T(32000)=5⋅10−8⋅320002=51.2T(32000)=5\cdot10^{-8}\cdot32000^2=51.2 s. Check: from 8000 to 32000 the size is multiplied by 4, the time by 42=164^2=16: 3.2⋅16=51.23.2\cdot16=51.2.

Exercise 2 (points 10)

A shop writes down, day by day, its gain in euros (a negative number is a loss). Write the class ArrayTasks with two static methods.

(a) (6 points) public static int bestStretch(int[] gains) returns the largest total gain over a stretch of one or more consecutive days, that is the largest sum of a non-empty run of consecutive elements.

  • Constraints: 1≤1\le gains.length ≤105\le 10^5, −104≤-10^4\le gains[i] ≤104\le 10^4 (the result fits in an int).
  • Required: time O(n)O(n) and O(1)O(1) extra memory.
gains result
{2, -4, 3, 5, -2, 4, -9, 1} 10
{-7, -3, -9} -3
{8} 8

(b) (4 points) public static void rotateRight(int[] a, int k) moves the elements of a to the right by k positions, the last elements coming back at the beginning, modifying a itself.

  • Constraints: 1≤1\le a.length ≤105\le 10^5, 0≤k≤1090\le k\le 10^9 (k can be larger than the length).
  • Required: time O(n)O(n) and O(1)O(1) extra memory: no second array (no new, no System.arraycopy into another array).
a k a after the call
{1, 2, 3, 4, 5, 6, 7} 3 {5, 6, 7, 1, 2, 3, 4}
{10, 20, 30, 40} 6 {30, 40, 10, 20}
{9} 100 {9}
Show the result

(a) Outputs 10, -3, 8. Time O(n)O(n), extra space O(1)O(1) (one pass, two int variables).

(b) Arrays after the call: {5, 6, 7, 1, 2, 3, 4}, {30, 40, 10, 20}, {9}. Time O(n)O(n) (about nn swaps), extra space O(1)O(1).

Show the full solution

Theory: 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 → (indices, length, loops with i < a.length), 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 → (static methods, private helpers, Math.max) and 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 →.

(a) Idea. The brute force tries every pair of ends i≤ji\le j and sums the run: O(n2)O(n^2) pairs with the inner sum cheap if updated step by step, O(n3)O(n^3) if recomputed. A single pass is enough. Call current the best sum of a run that ends exactly at the element examined. A run ending at gains[i] is either gains[i] alone or the best run ending at gains[i-1] extended by gains[i], so

current = max(gains[i], current + gains[i]).

(A negative current is worth nothing: it is better to restart.) The answer is the largest current seen, kept in best. Both are initialised with gains[0], not with 0, so that an array of only negative numbers gives the right answer -3 instead of 0.

Trace on {2, -4, 3, 5, -2, 4, -9, 1}:

i gains[i] current best
0 2 2 2
1 -4 -2 2
2 3 3 3
3 5 8 8
4 -2 6 8
5 4 10 10
6 -9 1 10
7 1 2 10

(b) Idea. Rotating right by shift =k mod n=k \bmod n (rotating by nn gives the same array, so only the remainder matters) can be done with three reversals: reverse the whole array, then reverse the first shift elements, then reverse the other n - shift. On {1,2,3,4,5,6,7} with shift = 3: {7,6,5,4,3,2,1}, then {5,6,7,4,3,2,1}, then {5,6,7,1,2,3,4}. A reversal swaps the two ends with one temporary int and moves inwards.

java
public class ArrayTasks
{
   /**
      Largest sum of a non-empty run of consecutive elements
      @param gains the daily gains (length at least 1)
      @return the largest sum
   */
   public static int bestStretch(int[] gains)
   {
      int best = gains[0];      // best sum of any run seen so far
      int current = gains[0];   // best sum of a run ending at index i
      for (int i = 1; i < gains.length; i++)
      {
         current = Math.max(gains[i], current + gains[i]);
         best = Math.max(best, current);
      }
      return best;
   }

   /**
      Rotates the array to the right by k positions, in place
      @param a the array
      @param k number of positions (k >= 0)
   */
   public static void rotateRight(int[] a, int k)
   {
      int n = a.length;
      int shift = k % n;           // k can be larger than n
      reverse(a, 0, n - 1);        // whole array
      reverse(a, 0, shift - 1);    // first shift elements
      reverse(a, shift, n - 1);    // the others
   }

   // reverses a[from..to] (both included); does nothing if from >= to
   private static void reverse(int[] a, int from, int to)
   {
      while (from < to)
      {
         int tmp = a[from];
         a[from] = a[to];
         a[to] = tmp;
         from++;
         to--;
      }
   }
}

Complexity. (a) One loop of n−1n-1 iterations, each with a constant number of operations: Θ(n)\Theta(n); memory: best, current, i, so O(1)O(1). (b) The three reversals perform n2+shift2+n−shift2=n\frac n2+\frac{shift}{2}+\frac{n-shift}{2}=n swaps: Θ(n)\Theta(n); memory: tmp and the indices, O(1)O(1). reverse is private because it is not part of the public interface.

Tests that were run (the code compiled and run on all the examples above, and compared with a brute force on 20 000 random arrays, including all-negative arrays, k larger than the length and k = 0): all matched; for example {5,-1,-1,-1,5} gives 7 and {1,2,3} with k = 0 is unchanged.

Typical errors. Initialising best with 0 (wrong when all numbers are negative); a loop i <= gains.length (ArrayIndexOutOfBoundsException); forgetting k % n (for k = 6 and n = 4, reverse(a, 0, 5) goes out of the array); using a second array when it is forbidden; calling a.length() instead of a.length.

Exercise 3 (points 12)

A weather station stores its temperature readings in a log of fixed capacity.

(a) (8 points) Write the class MeasurementLog with:

  • a constructor MeasurementLog(int capacity) that creates an empty log able to hold at most capacity readings (1 <= capacity <= 1000);
  • boolean add(double value): stores the reading and returns true; if the log is already full it does not change the log and returns false;
  • int size(): the number of readings stored;
  • double average(): the arithmetic mean of the stored readings, 0.0 if there are none;
  • int countAbove(double limit): how many stored readings are strictly greater than limit;
  • String toString(): the text MeasurementLog[size/capacity]: followed by every stored reading in order of insertion, each preceded by one space.

Instance variables must be private. add must take constant time; average and countAbove must take time proportional to the number of stored readings.

(b) (4 points) Write a class LogMain with a main method that reads from the standard input an integer (the capacity) followed by any number of readings separated by spaces or line breaks (decimal numbers with the point, for example 21.5), until the input ends. It stores the readings in a MeasurementLog, counting the ones that do not fit, and prints four lines:

Log: <the log>
Average: <average>
Above average: <number of readings strictly above the average>
Discarded: <number of readings that did not fit>

Examples (standard input on the left, output on the right):

4                               Log: MeasurementLog[4/4]: 21.5 23.0 19.5 20.0
21.5 23.0 19.5                  Average: 21.0
20.0 25.5                       Above average: 2
                                Discarded: 1
2                               Log: MeasurementLog[2/2]: 10.0 20.0
10.0 20.0 30.0 40.0             Average: 15.0
                                Above average: 1
                                Discarded: 2
5                               Log: MeasurementLog[0/5]:
                                Average: 0.0
                                Above average: 0
                                Discarded: 0
Show the result

The three examples above give exactly the outputs shown. Costs: add O(1)O(1); size O(1)O(1); average, countAbove and toString O(size)O(\text{size}) (one pass over the stored readings).

Show the full solution

Theory: 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 → (class, constructor, instance variables, Scanner, hasNextDouble, useLocale), 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 → (toString, println of an object uses toString), 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 → and 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 →.

Idea. A partially filled array: data has the capacity as length, and the integer count says how many cells are really used (the first count cells). add writes in data[count] and increases count; it first checks that count is not already data.length, otherwise it would throw ArrayIndexOutOfBoundsException. All the loops go up to count, not to data.length: the cells not used contain 0 and would spoil the average. main reads the capacity with nextInt() and then loops with hasNextDouble(), which is false at the end of the input; the result of add tells whether to count a discarded reading. Note that main calls log.average() twice with the same value: it could be saved in a variable.

java
public class MeasurementLog
{
   private double[] data;   // readings, stored in the first count cells
   private int count;       // number of readings stored

   /**
      Creates an empty log
      @param capacity maximum number of readings (at least 1)
   */
   public MeasurementLog(int capacity)
   {
      data = new double[capacity];
      count = 0;
   }

   /**
      Adds a reading if there is room
      @param value the reading
      @return true if stored, false if the log is full
   */
   public boolean add(double value)
   {
      if (count == data.length)
      {
         return false;
      }
      data[count] = value;
      count++;
      return true;
   }

   /**
      Number of readings stored
      @return the number of readings
   */
   public int size()
   {
      return count;
   }

   /**
      Arithmetic mean of the readings
      @return the mean, 0.0 if the log is empty
   */
   public double average()
   {
      if (count == 0)
      {
         return 0.0;
      }
      double sum = 0;
      for (int i = 0; i < count; i++)
      {
         sum = sum + data[i];
      }
      return sum / count;
   }

   /**
      Counts the readings strictly greater than a limit
      @param limit the limit
      @return how many readings are above it
   */
   public int countAbove(double limit)
   {
      int n = 0;
      for (int i = 0; i < count; i++)
      {
         if (data[i] > limit)
         {
            n++;
         }
      }
      return n;
   }

   /**
      Textual description: MeasurementLog[size/capacity]: r1 r2 ...
      @return the description
   */
   public String toString()
   {
      String s = "MeasurementLog[" + count + "/" + data.length + "]:";
      for (int i = 0; i < count; i++)
      {
         s = s + " " + data[i];
      }
      return s;
   }
}
java
import java.util.Scanner;
import java.util.Locale;
public class LogMain
{
   public static void main(String[] args)
   {
      Scanner in = new Scanner(System.in);
      in.useLocale(Locale.US);          // the decimal separator is the point

      int capacity = in.nextInt();
      MeasurementLog log = new MeasurementLog(capacity);
      int discarded = 0;
      while (in.hasNextDouble())        // false when the input ends
      {
         double value = in.nextDouble();
         if (!log.add(value))
         {
            discarded++;
         }
      }
      in.close();

      System.out.println("Log: " + log);              // uses toString()
      System.out.println("Average: " + log.average());
      System.out.println("Above average: " + log.countAbove(log.average()));
      System.out.println("Discarded: " + discarded);
   }
}

Trace of example 1. Capacity 4. The readings 21.5, 23.0, 19.5, 20.0 fill the four cells (count goes 1, 2, 3, 4); 25.5 finds count == data.length, add returns false, so discarded becomes 1. Average: (21.5+23.0+19.5+20.0)/4=84/4=21.0(21.5+23.0+19.5+20.0)/4=84/4=21.0. Readings strictly above 21.0: 21.5 and 23.0, so 2. The data were chosen as multiples of 0.50.5, which are exact in binary floating point, so the printed average is exact (compare Representation of InformationEverything in a computer is a sequence of bits, so each kind of information needs a coding. Natural numbers use positional notation in base 2 (conversion by repeated division by 2); signed integers use two's complement (range from minus 2 to the n minus 1 up to 2 to the n minus 1, minus 1), where negation is invert-all-bits-and-add-1, sums are plain binary sums and overflow is detected on the two top carries; hexadecimal groups bits in fours; fractions use fixed point or IEEE 754 floating point (sign, exponent in excess 127, 23-bit fraction) and are only approximate; characters are unsigned integers in a code table (ASCII, Unicode); images, video and sound are stored as numbers too (pixels, frame differences, samples).Representation of Information →: most decimals such as 0.350.35 are not).

Complexity. add: a comparison and an assignment, Θ(1)\Theta(1). average and countAbove: one loop over count readings with constant body, Θ(size)\Theta(\text{size}). toString visits the readings once (the string concatenation also copies characters, which we do not count).

Tests that were run. Both classes were compiled and run on the three examples above: the outputs are exactly the ones shown.

Typical errors.

  • Looping to data.length instead of count (average divided by the wrong number or including zeros).
  • Not checking for a full log in add (run-time exception), or checking count > data.length (one reading too late).
  • Declaring the instance variables inside the constructor (double[] data = new double[capacity]; creates a local variable and the field stays null).
  • Calling in.next() instead of in.nextDouble(), or calling hasNextDouble() and forgetting to read the value (infinite loop).
  • Comparing double values with == (here only > is needed).
  • Dividing by count when it is zero: handled by the first if in average.
Self-assessment grid
Exercise Points What you need for full marks Typical errors
1, questions 1-3 3 205=0xCD=110011012205=\texttt{0xCD}=11001101_2; −45=0xD3-45=\texttt{0xD3} (invert and add 1); 1010 0111 is 167 unsigned and −89-89 in two's complement stopping the division at quotient 1; forgetting "add 1"; giving only one reading of the pattern
1, question 4 1 result 1000 1100 =−116=-116 and overflow declared adding in decimal and saying "140"; not noticing that two positives gave a negative
1, questions 5-6 2 0xC0D80000 (exponent 129129, fraction 1011); 0x42F60000 =123=123 forgetting the bias 127 or the implicit leading 1; wrong sign bit
1, questions 7-8 2 1 ms, 20 ms, 1000 s; b=2b=2 and 51.2 s nlog⁡nn\log n with the wrong power of ten; using b=log⁡23.2/0.8b=\log_2 3.2/0.8 without the ratio; linear prediction (6.4 s)
2(a) 6 one loop with max(gains[i], current + gains[i]); best and current start at gains[0]; O(n)O(n), O(1)O(1); correct on all-negative arrays start at 0; two nested loops (O(n2)O(n^2)); index out of range
2(b) 4 k % n; three reversals; no second array; O(n)O(n), O(1)O(1) no k % n; shifting by one position kk times (O(nk)O(nk)); extra array
3(a) 8 private double[] data and int count; constructor builds the array; add checks room; loops up to count; toString in the required format loops up to data.length; local variable shadowing the field; wrong text format
3(b) 4 Scanner with Locale.US; nextInt() then while (in.hasNextDouble()); counts discarded readings; four lines printed in the required format next() without reading; no in.useLocale (comma expected in some systems); not using the boolean returned by add