Foundations of Computer Science - Mock Exam 3
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 exams of the equivalent Italian-language course (Fondamenti di Informatica, Information Engineering, UniPD): short theory questions with execution traces, then programming problems in Java. It is not an official exam. Proposed duration: 2 hours. Total: 30 points. Exercise 1 (theory, 8 questions of 1 point each) is worth 8 points, Exercise 2 is worth 10 points and Exercise 3 is worth 12 points. Allowed material: none.
In the programming exercises, write complete Java methods. State the time complexity that is asked for, and respect the limits on the input. The Java solutions below were compiled and run on all the examples, plus a random check against a reference implementation.
Exercise 1 (points 8)
Answer the eight questions below (1 point each). Answers are an output, a list, a number or a letter; no justification is needed on the exam, but a trace helps.
1. What does the program print?
a = [4, 8, 15, 16, 23, 42]
print(a[1:4], a[:2], a[4:], len(a[2:]))2. What does the program print?
def f(lst, x):
lst.append(x)
lst = lst[:2]
return lst
a = [1, 2, 3]
b = f(a, 4)
print(a, b)3. The file n.txt contains three lines: 5, 10, 15 (each line ends with a newline, so the file has 8 characters). What do the two programs print?
# program A
count = 0
with open("n.txt", "r", encoding="utf-8") as file:
content = file.read()
for item in content:
count = count + 1
print(count)
# program B
count = 0
with open("n.txt", "r", encoding="utf-8") as file:
for line in file:
count = count + 1
print(count)4. Selection sort (the course version: the minimum of the unsorted part is searched, and a swap is done only if the minimum is not already in place) sorts [6, 3, 9, 2, 5] in ascending order. Write the list at the end of the outer-loop iteration with i = 1 (the second iteration), and the total number of swaps done by the whole algorithm.
5. Insertion sort (the course version) sorts [5, 1, 4, 2, 3] in ascending order. Write the list at the end of the outer-loop iteration with i = 2, and the total number of executions of the shift a[j + 1] = a[j].
6. A stable sorting algorithm keeps records with equal keys in their original relative order. The list of pairs [(2, 'a'), (1, 'b'), (2, 'c'), (1, 'd')] is sorted by the first element only (the comparison looks only at the first element and is a strict <, as in the course code) with selection sort, insertion sort and merge sort. Which of the three algorithms leave the pairs with equal keys in their original order?
- a. all three
- b. insertion sort and merge sort only
- c. insertion sort only
- d. none of them
7. With the cost model of the course (count the accesses to list elements), compute the cost of: selection sort on any list of 10 elements; insertion sort on a list of 10 elements already sorted; insertion sort on a list of 10 elements sorted in reverse order.
8. merge_sort (the course version, which calls itself on the two halves obtained with slicing and then calls merge) is executed on a list of 6 elements. How many calls of merge_sort happen in total (the first one included), and how many calls of merge?
Show the result
[8, 15, 16] [4, 8] [23, 42] 4[1, 2, 3, 4] [1, 2]- Program A prints
8, program B prints3. - List
[2, 3, 9, 6, 5]; 2 swaps in total. - List
[1, 4, 5, 2, 3]; 6 shifts in total. - c (insertion sort only).
- Selection sort: 90. Insertion sort, sorted list: 27. Insertion sort, reversed list: 153.
- 11 calls of
merge_sort, 5 calls ofmerge.
Show the full solution
1. Slicing. The left bound is included and the right bound is excluded. a[1:4] takes the indices 1, 2, 3: [8, 15, 16]. a[:2] goes from the start to index 1: [4, 8]. a[4:] goes from index 4 to the end: [23, 42]. a[2:] is [15, 16, 23, 42], which has length 4. Typical mistake: including the right bound (a[1:4] with four elements). See Python - Control Flow, Lists, Functions and FilesA program makes decisions with if, elif and else, whose blocks are defined by the colon and by four-space indentation (an IndentationError otherwise). It repeats statements with while loops (condition, counter, update; infinite loops and sentinel loops) and for loops over range or over a sequence. A list is an ordered mutable container with zero-based indices, len, append, insert, pop, remove, the in operator, slicing, and sorted versus sort. Functions are defined with def, take parameters, return values with return (print is not return; no return gives None), have local variables, must be defined before being called and can live in separate modules imported with import. Text files are opened with the with statement in modes r, w or a with utf-8 encoding and read as strings.Python - Control Flow, Lists, Functions and Files →.
2. A function that changes a list. The list [1, 2, 3] is passed by object reference: lst and a are two names of the same list, so lst.append(4) changes a, which becomes [1, 2, 3, 4]. The next line, lst = lst[:2], does not change the list: the slice builds a new list [1, 2] and the name lst is rebound to it, while a still refers to the old list. The function returns the new list, so b is [1, 2]. Typical mistake: answering [1, 2] [1, 2] (thinking that the assignment changes a too), or [1, 2, 3] [1, 2] (forgetting the append).
3. Characters or lines. file.read() returns the whole content as one string: "5\n10\n15\n". The for loop over a string visits characters: 5, newline, 1, 0, newline, 1, 5, newline are 8 characters, so program A prints 8. A for loop over the file object visits lines, and there are 3: program B prints 3. Typical mistake: forgetting that a newline is a character, or that read() gives a string and not a list of lines.
4. Selection sort. Trace (the swap is done only when the position of the minimum is different from i):
i |
unsorted part | minimum (position) | list after the iteration |
|---|---|---|---|
| 0 | [6, 3, 9, 2, 5] |
2 (index 3) | [2, 3, 9, 6, 5] (swap) |
| 1 | [3, 9, 6, 5] |
3 (index 1) | [2, 3, 9, 6, 5] (no swap) |
| 2 | [9, 6, 5] |
5 (index 4) | [2, 3, 5, 6, 9] (swap) |
| 3 | [6, 9] |
6 (index 3) | [2, 3, 5, 6, 9] (no swap) |
At the end of i = 1 the list is still [2, 3, 9, 6, 5], because the minimum 3 is already in place. Total swaps: 2. Typical mistake: counting a swap also when the minimum is already in place (that would give 4). See Searching and Sorting AlgorithmsLinear search scans left to right and returns the index of the first occurrence or -1 (worst and average case O(n), works on any list). Binary search needs a SORTED list: it compares with the middle element and keeps one half, so T(n) = T(n/2) + 1, i.e. O(log n) (recursive, two base cases: empty interval -> -1, element found; tail recursive, so a loop version exists). Finding max/min always reads all n elements: Theta(n). Sorting: selection sort (find the minimum of the unsorted part, swap it in place) is always O(n^2), T(n) = n^2/2 + 9n/2 - 5 counting list accesses; insertion sort (insert the next element into the sorted left part by shifting) costs O(n) on sorted data and O(n^2) in the average and worst case; MergeSort (split, sort both halves recursively, merge) has T(n) = 2T(n/2) + 5n, i.e. O(n log n), at the price of extra memory. Recurrences are solved by successive substitution; general form T(n) = aT(n/b) + f(n) (Master Theorem). Not every recursion is efficient: naive recursive Fibonacci, T(n) = T(n-1) + T(n-2) + 1, is exponential (about phi^n calls), while the iterative version is O(n).Searching and Sorting Algorithms →.
5. Insertion sort. Each shift moves one element of the sorted part one place to the right.
i |
element cur |
elements shifted | list after the iteration |
|---|---|---|---|
| 1 | 1 | 5 (1 shift) | [1, 5, 4, 2, 3] |
| 2 | 4 | 5 (1 shift) | [1, 4, 5, 2, 3] |
| 3 | 2 | 5, 4 (2 shifts) | [1, 2, 4, 5, 3] |
| 4 | 3 | 5, 4 (2 shifts) | [1, 2, 3, 4, 5] |
After i = 2: [1, 4, 5, 2, 3]. Total shifts: . Each shift removes exactly one pair of elements that are out of order, and the list has 6 such pairs: (5,1), (5,4), (5,2), (5,3), (4,2), (4,3). This is why the cost of insertion sort depends on how disordered the data is.
6. Stability. The traces use the comparison on the first element only; equal keys are written with their label.
- Insertion sort: the inner loop shifts an element only if it is strictly greater than
cur, socurstops after the elements with an equal key. Result:(1,'b'), (1,'d'), (2,'a'), (2,'c'). The pairs with the same key are in the original order: stable. - Selection sort: after
i = 0the first minimum,(1,'b'), is swapped with(2,'a'):[(1,'b'), (2,'a'), (2,'c'), (1,'d')]. Afteri = 1the minimum of the rest is(1,'d')at index 3, swapped with(2,'a'):[(1,'b'), (1,'d'), (2,'c'), (2,'a')]. The two pairs with key 2 are now in the orderc, a: the long-distance swap sent(2,'a')behind(2,'c'). Not stable. - Merge sort with the course
merge, which writes the element of the first half only ifb[ib] < c[ic]and otherwise the element of the second half. The halves[(2,'a'), (1,'b')]and[(2,'c'), (1,'d')]become[(1,'b'), (2,'a')]and[(1,'d'), (2,'c')]. When the merge compares(1,'b')and(1,'d')the keys are equal,<is false, and the element of the second half goes first: result(1,'d'), (1,'b'), (2,'c'), (2,'a'). Both pairs of equal keys are reversed: not stable. Writing<=inmergewould make it stable.
So only insertion sort keeps the original order: answer c. The label sequences are b d a c (insertion), b d c a (selection), d b c a (merge). Stability matters when data are sorted twice, for example by name and then by score. Typical mistake: thinking that "merge sort is the good algorithm, so it is stable": it depends on the < or <= in the merge.
- selection sort, any list: , so (the same for all data);
- insertion sort, already sorted (best case): , so ;
- insertion sort, reversed (worst case): , so .
Typical mistake: believing that selection sort is faster on sorted data (it always does the same work), or using without the lower-order terms when the exact count is asked. See also 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 →.
8. Calls of merge sort. Let be the number of calls on a list of elements: for (base case), otherwise (the call itself and the two halves). Then , , , and . The merge is called once for each call that has at least 2 elements. These are the internal nodes of the tree of calls: (6 leaves with one element each). In general, for elements there are leaves and calls of merge. See RecursionA function is recursive when it calls itself; it is correct only if it has at least one base case that needs no recursive call and if every recursive call works on a simpler problem that gets closer to a base case (otherwise Python stops with RecursionError, the limit being 1000 nested calls). Each pending call is a record on the call stack. Types: linear (one call, e.g. factorial), binary (two calls, e.g. sum of a list by halves), tail (the call is the last action, solved with an accumulator and easy to turn into a loop), multiple (fib_bad recomputes the same values and explodes). Typical examples: factorial, Fibonacci, reversing a string, Towers of Hanoi (2^n - 1 moves). Recursion is elegant for naturally recursive problems but usually less efficient than a loop.Recursion →.
Exercise 2 (points 10)
A game stores its results in Player objects (name and points). The class is given:
public class Player
{ private String name;
private int points;
public Player(String aName, int aPoints)
{ name = aName;
points = aPoints;
}
public String getName() { return name; }
public int getPoints() { return points; }
public String toString()
{ return name + ":" + points;
}
}In the examples a player is written as name:points.
a) (5 points) Write the method public static void insertionSort(Player[] a) that sorts the array in place by points in descending order, with the insertion sort algorithm. Players with equal points must keep the order they had in the input (the sort must be stable). No other array may be used.
Constraints: a.length ; points ; no element is null.
Examples:
- Input
[Ann:50, Bob:80, Cleo:50, Dan:70]gives[Bob:80, Dan:70, Ann:50, Cleo:50]. - Input
[Zoe:90, Yan:90, Xia:90]gives[Zoe:90, Yan:90, Xia:90]. - Input
[]gives[].
b) (3 points) Write the method public static Player[] merge(Player[] x, Player[] y). The arrays x and y are already sorted by points in descending order. The method returns a new array with all the players of x and y, sorted by points in descending order; when two players have equal points, the one of x comes before the one of y, and players of the same array keep their order. The arrays x and y are not modified. Required time: , with and the lengths of x and y.
Examples:
x = [Bob:80, Ann:50],y = [Dan:70, Eve:50, Fay:20]gives[Bob:80, Dan:70, Ann:50, Eve:50, Fay:20].x = [],y = [Gus:5]gives[Gus:5].x = [Hal:40, Ida:40],y = [Joe:40]gives[Hal:40, Ida:40, Joe:40].
c) (2 points) Count how many times your insertionSort compares the points of two players on the first example of part a (do not count a comparison that is not executed because the index is out of range). Then give the number of comparisons in the best and in the worst case for an array of players, and describe an input that gives each case.
Show the result
a) [Bob:80, Dan:70, Ann:50, Cleo:50], [Zoe:90, Yan:90, Xia:90], []. Time in the worst case, in the best case, extra memory .
b) [Bob:80, Dan:70, Ann:50, Eve:50, Fay:20], [Gus:5], [Hal:40, Ida:40, Joe:40]. Time , extra memory (the returned array).
c) 5 comparisons on the first example. Best case (array already in descending order); worst case (points in strictly ascending order, so that every player moves to the front).
Show the full solution
a) Insertion sort. The idea is the one of Searching and Sorting AlgorithmsLinear search scans left to right and returns the index of the first occurrence or -1 (worst and average case O(n), works on any list). Binary search needs a SORTED list: it compares with the middle element and keeps one half, so T(n) = T(n/2) + 1, i.e. O(log n) (recursive, two base cases: empty interval -> -1, element found; tail recursive, so a loop version exists). Finding max/min always reads all n elements: Theta(n). Sorting: selection sort (find the minimum of the unsorted part, swap it in place) is always O(n^2), T(n) = n^2/2 + 9n/2 - 5 counting list accesses; insertion sort (insert the next element into the sorted left part by shifting) costs O(n) on sorted data and O(n^2) in the average and worst case; MergeSort (split, sort both halves recursively, merge) has T(n) = 2T(n/2) + 5n, i.e. O(n log n), at the price of extra memory. Recurrences are solved by successive substitution; general form T(n) = aT(n/b) + f(n) (Master Theorem). Not every recursion is efficient: naive recursive Fibonacci, T(n) = T(n-1) + T(n-2) + 1, is exponential (about phi^n calls), while the iterative version is O(n).Searching and Sorting Algorithms →: the left part of the array is sorted; at each step the player cur = a[i] is inserted in the left part by shifting to the right the players that must come after it. Here "must come after" means strictly fewer points (the order is descending), so the loop condition is a[j].getPoints() < cur.getPoints().
The strict < gives the stability: cur stops as soon as it meets a player with equal points, so it is written after the players that were already there with the same points. With <= the new element would jump over its equals and reverse the ties (Cleo would come before Ann in the first example).
An array of objects holds references: the shifts copy references, not Player objects (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 test j >= 0 comes first in the condition, and && does not evaluate its right operand when the left one is false, so a[-1] is never read (reading it would throw ArrayIndexOutOfBoundsException, see 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 methods are static and use only their arguments (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 →); the getters of Player are the ones of 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 →.
public class Ranking
{ // sorts a by points, descending; equal points keep the input order
public static void insertionSort(Player[] a)
{ for (int i = 1; i < a.length; i++)
{ Player cur = a[i]; // the player to insert
int j = i - 1;
// shift right the players with strictly fewer points than cur
while (j >= 0 && a[j].getPoints() < cur.getPoints())
{ a[j + 1] = a[j];
j--;
}
a[j + 1] = cur; // final position of cur
}
}
// b) merge of two arrays sorted in descending order
public static Player[] merge(Player[] x, Player[] y)
{ Player[] r = new Player[x.length + y.length];
int i = 0, j = 0, k = 0;
while (i < x.length && j < y.length)
{ if (x[i].getPoints() >= y[j].getPoints()) // >= : on a tie x goes first
r[k++] = x[i++];
else
r[k++] = y[j++];
}
while (i < x.length) r[k++] = x[i++]; // leftover of x
while (j < y.length) r[k++] = y[j++]; // leftover of y
return r;
}
public static void main(String[] args)
{ Player[] a = { new Player("Ann", 50), new Player("Bob", 80),
new Player("Cleo", 50), new Player("Dan", 70) };
insertionSort(a);
System.out.println(java.util.Arrays.toString(a));
Player[] x = { new Player("Bob", 80), new Player("Ann", 50) };
Player[] y = { new Player("Dan", 70), new Player("Eve", 50), new Player("Fay", 20) };
System.out.println(java.util.Arrays.toString(merge(x, y)));
}
}The program prints [Bob:80, Dan:70, Ann:50, Cleo:50] and [Bob:80, Dan:70, Ann:50, Eve:50, Fay:20]. Trace of the first example: i = 1, cur = Bob:80: Ann has fewer points, so Ann is shifted: [Bob, Ann, Cleo, Dan]. i = 2, cur = Cleo:50: Ann has 50, and is false, so no shift: [Bob, Ann, Cleo, Dan]. i = 3, cur = Dan:70: Cleo (50) and Ann (50) are shifted, Bob (80) is not: [Bob, Dan, Ann, Cleo].
Cost. The outer loop runs times. The inner loop runs between 0 and times, depending on the data: if the array is already in descending order the condition is false at once (best case, comparisons, time); if the points are in ascending order every element goes to the front and the comparisons are (worst case, ). With the worst case is about comparisons. Only a few variables are used besides the array: extra memory.
b) Merge. Two indices i and j point to the first player not yet copied in x and in y; the index k is the next free place of the result r (the same merge as in merge sort, Searching and Sorting AlgorithmsLinear search scans left to right and returns the index of the first occurrence or -1 (worst and average case O(n), works on any list). Binary search needs a SORTED list: it compares with the middle element and keeps one half, so T(n) = T(n/2) + 1, i.e. O(log n) (recursive, two base cases: empty interval -> -1, element found; tail recursive, so a loop version exists). Finding max/min always reads all n elements: Theta(n). Sorting: selection sort (find the minimum of the unsorted part, swap it in place) is always O(n^2), T(n) = n^2/2 + 9n/2 - 5 counting list accesses; insertion sort (insert the next element into the sorted left part by shifting) costs O(n) on sorted data and O(n^2) in the average and worst case; MergeSort (split, sort both halves recursively, merge) has T(n) = 2T(n/2) + 5n, i.e. O(n log n), at the price of extra memory. Recurrences are solved by successive substitution; general form T(n) = aT(n/b) + f(n) (Master Theorem). Not every recursion is efficient: naive recursive Fibonacci, T(n) = T(n-1) + T(n-2) + 1, is exponential (about phi^n calls), while the iterative version is O(n).Searching and Sorting Algorithms →). At each step the player with more points is copied. The test is >=: when the points are equal the player of x is copied first, which is the required tie rule. Then, when one array is finished, the last two loops copy what is left in the other one (only one of them does something). The loops execute writes in total, one for each element of r, and every iteration costs a constant time: . The inputs are only read. The new array contains the same Player objects (the references are copied, not the objects). Typical mistakes: using > instead of >= (ties reversed), forgetting the leftover loops (players lost), writing the result into x.
Trace of the first example: Bob:80 vs Dan:70 Bob; Ann:50 vs Dan:70 Dan; Ann:50 vs Eve:50 Ann (tie, x first); x is finished (3 comparisons), the leftover loop copies Eve:50 and Fay:20. For the third example all the points are equal and the result is x followed by y.
c) Counting. First example, [Ann:50, Bob:80, Cleo:50, Dan:70]: i = 1: Ann against Bob (1 comparison), after the shift and the loop stops without comparing; i = 2: Ann against Cleo (1 comparison, false); i = 3: Cleo against Dan, Ann against Dan, Bob against Dan (3 comparisons, the last false). Total: comparisons (and 3 shifts). For the best case ( comparisons) and the worst case () see the cost analysis of part a; for example, [A:1, B:2, C:3, D:4] costs 6 comparisons and [D:4, C:3, B:2, A:1] only 3. The numbers were checked by running an instrumented version.
Exercise 3 (points 12)
A table of integers with rows and columns is stored row by row in a one-dimensional array t of length : the element in row and column (both counted from 0) is t[i * n + j]. For example the table with rows [1, 2, 3] and [4, 5, 6] (, ) is stored as {1, 2, 3, 4, 5, 6}.
Constraints: ; the length of t is exactly ; every element of t is between and .
a) (3 points) Write public static int[] rowSums(int[] t, int m, int n), which returns an array of length with the sum of each row, and public static int[] colSums(int[] t, int m, int n), which returns an array of length with the sum of each column.
b) (3 points) Write public static int[] transpose(int[] t, int m, int n), which returns a new array with the transposed table (it has rows and columns, also stored row by row). The array t is not modified.
c) (4 points) A saddle point is an element that is the smallest of its row and the largest of its column. Write public static int saddle(int[] t, int m, int n), which returns the index in t (that is, i * n + j) of a saddle point, or if there is none. Assume that all the elements of the table are different. Required: time and extra memory.
d) (2 points) State the time complexity of the four methods and the extra memory of each (the returned array is not extra memory for rowSums, colSums and transpose). How many element reads would the method of part c need if, for every element, you scanned its whole row and its whole column? Give the order of growth and the number for .
Examples:
t = {1, 2, 3, 4, 5, 6}, , :rowSumsgives[6, 15],colSumsgives[5, 7, 9],transposegives[1, 4, 2, 5, 3, 6].t = {5, 0, -2, 7}, , :rowSumsgives[10],colSumsgives[5, 0, -2, 7],transposegives[5, 0, -2, 7].t = {2, 9, 4}, , :rowSumsgives[2, 9, 4],colSumsgives[15],transposegives[2, 9, 4].saddleon{7, 2, 9, 8, 5, 6, 3, 4, 1}, gives4.saddleon{1, 2, 3, 4, 5, 6}, , gives3.saddleon{1, 4, 3, 2}, gives-1.
Show the result
a) and b): the outputs listed in the three examples above (rowSums, colSums, transpose).
c) 4, 3, -1 on the three saddle examples.
d) rowSums, colSums, transpose, saddle: all time. Extra memory: (besides the result) for the first three, for saddle. Scanning the row and the column of every element: reads, that is for , against about for the method of part c.
Show the full solution
The index formula. In row-by-row storage, before row there are complete rows of elements, so the element is at position . The same formula works for any table because only (the length of a row) is needed. A table stored in a single array is an ordinary 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 →): indices run from 0 to t.length - 1, and the loops use <. Index arithmetic is the key to the whole exercise.
a) Sums. Two nested loops visit every element once. For rowSums the sum of row i is accumulated in s[i]; for colSums the sum of column j is accumulated in s[j]. The only difference is which index is used for the result: the array is created with places for the rows and for the columns (new int arrays start at 0, 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 →). With elements between and , a row or column has at most 1000 elements, so a sum is at most in absolute value and fits easily in an int.
b) Transpose. The element in row and column of the table becomes the element in row and column of the transposed table. The transposed table has rows of elements, so its position is : the row length of the result is , not . Typical mistake: writing r[j * n + i], which is right only for square tables and for other shapes writes out of the array or overwrites elements.
c) Saddle point. The direct idea, checking each element against its row and column, costs too much (part d). Better: precompute the minimum of each row and the maximum of each column with a single pass, then do a second pass that looks for an element equal to both. The arrays rowMin (length ) and colMax (length ) are initialised with the first element of each row and column; the extra memory is numbers. The two passes cost steps: .
Because all the elements are different, there is at most one saddle point: if there were two, at and at , they would not be in the same row (two different row minima in the same row are impossible) nor in the same column, and then , a contradiction. This is why the method may return the first one found.
The complete program with the four methods:
public class Table
{ // t holds an m x n table row by row: t[i * n + j] is row i, column j
public static int[] rowSums(int[] t, int m, int n)
{ int[] s = new int[m];
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
s[i] += t[i * n + j];
return s;
}
public static int[] colSums(int[] t, int m, int n)
{ int[] s = new int[n];
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
s[j] += t[i * n + j];
return s;
}
// the transposed table has n rows and m columns
public static int[] transpose(int[] t, int m, int n)
{ int[] r = new int[m * n];
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
r[j * m + i] = t[i * n + j];
return r;
}
// index of an element that is the smallest of its row and the largest
// of its column, or -1
public static int saddle(int[] t, int m, int n)
{ int[] rowMin = new int[m];
int[] colMax = new int[n];
for (int i = 0; i < m; i++) rowMin[i] = t[i * n]; // first element of row i
for (int j = 0; j < n; j++) colMax[j] = t[j]; // first element of column j
for (int i = 0; i < m; i++) // pass 1: minima and maxima
for (int j = 0; j < n; j++)
{ int v = t[i * n + j];
if (v < rowMin[i]) rowMin[i] = v;
if (v > colMax[j]) colMax[j] = v;
}
for (int i = 0; i < m; i++) // pass 2: look for the saddle
for (int j = 0; j < n; j++)
{ int v = t[i * n + j];
if (v == rowMin[i] && v == colMax[j])
return i * n + j;
}
return -1;
}
public static void main(String[] args)
{ int[] t = { 1, 2, 3, 4, 5, 6 };
System.out.println(java.util.Arrays.toString(rowSums(t, 2, 3)));
System.out.println(java.util.Arrays.toString(colSums(t, 2, 3)));
System.out.println(java.util.Arrays.toString(transpose(t, 2, 3)));
int[] u = { 7, 2, 9, 8, 5, 6, 3, 4, 1 };
System.out.println(saddle(u, 3, 3));
System.out.println(saddle(t, 2, 3));
int[] w = { 1, 4, 3, 2 };
System.out.println(saddle(w, 2, 2));
}
}The program prints [6, 15], [5, 7, 9], [1, 4, 2, 5, 3, 6], 4, 3, -1. Trace of the first saddle example: the table is the rows [7, 2, 9], [8, 5, 6], [3, 4, 1]; the row minima are 2, 5, 1, and the column maxima are 8, 5, 9. The element 5 (row 1, column 1) is equal to both rowMin[1] and colMax[1]: index . In the third example the row minima are 1 and 2, the column maxima are 3 and 4: no element is equal to both, so the result is -1. In the second example the saddle point is 4: it is the smallest of its row [4, 5, 6] and the largest of its column [1, 4], at index .
Typical mistakes: initialising rowMin and colMax with 0 (wrong when all the values of a row are positive: the minimum would be 0), looping with i <= m, mixing and in i * n + j, returning the pair instead of the flat index.
d) Complexity. Each of the three first methods has two nested loops with and iterations and a constant cost inside: (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 cost is the number of executions of the innermost statement). Extra memory: rowSums, colSums and transpose allocate only the returned array (, and elements). saddle allocates rowMin and colMax: . The naive method, which for each of the elements scans its row ( reads) and its column ( reads), costs reads; for this is , about 670 times more than the reads of the two passes. The price of the fast method is the extra numbers: memory is traded for time.
Self-assessment grid
| Exercise | Points | What must be there for full points | Typical mistakes |
|---|---|---|---|
| 1 (questions 1-3, Python) | 3 (1 each) | exact output, including the brackets of the lists; the new list created by the slice in question 2; 8 characters against 3 lines in question 3 | right bound of a slice included; assignment lst = lst[:2] believed to change the caller's list; newline not counted as a character |
| 1 (questions 4-5, traces) | 2 (1 each) | the list after the requested iteration and the count of swaps or shifts | counting a swap when the minimum is in place; confusing the number of shifts with the number of outer iterations |
| 1 (question 6, stability) | 1 | answer c, with the idea that the shifts stop at equal keys, while the long-distance swap and the < of the merge break the order |
answering that merge sort is always stable; forgetting that selection sort swaps over distant elements |
| 1 (questions 7-8, costs) | 2 (1 each) | 90, 27, 153; 11 calls and 5 merges | using only the dominant term; counting the leaves as merges |
| 2 a | 5 | in-place insertion sort, descending, with the strict <, test j >= 0 first, final write a[j + 1] = cur |
<= that reverses the ties; a[j] read before checking j >= 0; losing cur by overwriting it |
| 2 b | 3 | new array of length , comparison >=, two leftover loops, |
> that reverses the ties; leftovers forgotten; the result written into x |
| 2 c | 2 | 5 comparisons; best case on a sorted array; worst case on the reversed order | counting also the comparison with j = -1; swapping best and worst case |
| 3 a | 3 | arrays of length and , index i * n + j, loops with < |
result array with the wrong length; <= in the loops |
| 3 b | 3 | new array of length , destination index j * m + i |
j * n + i (right only for square tables); transposing in place |
| 3 c | 4 | row minima and column maxima in two arrays, a second pass looking for the equal element, returned flat index, | arrays initialised with 0; scanning row and column for every element; returning |
| 3 d | 2 | for all, extra memory for saddle, for the naive method |
forgetting the extra memory; without distinguishing and |