UNIVERSITY OF EDINBURGH course CS0077 COLLEGE OF SCIENCE AND ENGINEERING SCHOOL OF INFORMATICS Computer Science 1 Ah Resit Examination Specimen Solutions Date: Monday 1st September 2003 Time: 09:30 11:00 (one and a half hours) Place: Adam House Room: Ground Floor Board of examiners Chair: M. R. Jerrum External Examiner: R. Dyckhoff Notes about Specimen Solutions 1. These specimen solutions are issued for guidance only, to help as a revision aid. They do not represent a complete picture of how the exam was marked; they are specimen solutions, not a marking guide. 2. The solutions typically present one answer from a set of possible answers. Often, answers which have alternative wording or different technical details are equally acceptable. 3. If you have any questions concerning these solutions, please contact the course organiser. Please note that the course organiser will not be able to answer questions about the marking of the exam.
Question 1 (a) Fill in the type and value of each of the Java expressions which is printed out by the code fragment shown below. Assume that the statements are executed in order. [7 marks] String x = "Nunavut"; int b = 7; Type: Value: System.out.println(x + b); String "Nunavut7" System.out.println(x.length() + b); int 14 System.out.println(x.length() == b); boolean true double d = 2.4; System.out.println((int)d * (float)d); float 4.8 Object o1 = new Object(); Object o2 = new Object(); System.out.println(o1 == o2); boolean false o1 = null; o2 = null; System.out.println((o1 == o2)? y : n ); char y (b) Operators and methods in Java can be overloaded. Explain the meaning of this term, using one of the expressions above as an example. [3 marks] An overloaded operator or method is one which has the same name, but different underlying implementations for different types. An example from above is the use of the operator +. In the first System.out line, + stands for concatenation of strings; in the second output line, + stands for integer addition.
Question 2 (a) A company has been using a software inspection process to help ensure that their programs do not contain certain kinds of defect. The company wishes to switch from their previous programming language, which provided few built-in checks, to Java, which provides strong typing and other static analysis mechanisms during compilation. Using your knowledge of the Java language, say which of the following manual checks will still be necessary when code is compiled with the Java compiler javac, and which checks will no longer be needed. Place a tick in the box if the manual check is still necessary with Java, and a cross otherwise. [6 marks] Do arithmetic expressions have only numerically typed operands? Is every field of a new object initialized? Are any variables referenced before initialization? Is the upper bound of array accesses length-1 and not length? Is every method invocation on a non-null object? Do all method calls have the correct number of parameters? (b) The spiral model of the software production process considers software construction as an iterative process, revolving through four quadrants. Give a brief outline of the process and mention some of its advantages. [4 marks]
The spiral model looks like this: Planning Customer evaluation Risk analysis Engineering The process starts in the planning stage, and after each step of risk assessment it can be decided whether to proceed forward. Advantages of the model are that the iterative nature allows flexibility (the model is robust), and that it is visible, since it requires that each prototype is documented.
Question 3 A ternary tree is a like a binary tree, except that each node has up to three children in a given order: a left child, a middle child, and a right child. (a) In terms of n, how many leaves does a complete ternary tree of height n have? 3 n [1 mark] (b) Define a class TernaryTree for representing nodes of ternary trees in Java. As with the representation of binary trees in lectures, use the null object for empty trees, so that objects from your class can be used for nodes with one or more children missing. Each non-empty node should store a character item. No methods are required for this part of the question. [4 marks] class TernaryTree { char item; TernaryTree left; TernaryTree middle; TernaryTree right; (c) Write a static method lookup for your class that takes a character and a TernaryTree object as arguments and has TernaryTree result type. The method should treat the ternary tree argument as a binary search tree by ignoring the middle children of the nodes in the tree. If it finds the character argument at some node of the search tree, the middle child of that node should be returned. If the character argument is not found, null should be returned instead. Such a method could be used to treat a ternary tree as a trie. [5 marks] public static TernaryTree lookup(char a, TernaryTree t) { if (t == null) return null; if (a == t.item) return t.middle; if (a < t.item) return lookup(a, t.left); else return lookup (a, t.right);
Question 4 (a) Consider the following Java class definitions (Note: it is deliberate that there are no fields and that the methods do nothing!). class C1 { public void twiddle () { public void fiddle () { class C2 extends C1 { public void flip () { public void flop () { How many different methods can be invoked on an object of class C1? Ignore methods from the Object class that are available in every class. 2 [1 mark] How many different methods can be invoked on an object of class C2? Again ignore methods from the Object class. 4 [1 mark] (b) Consider the following Java fragment. C2 x = new C2(); C1 y = x; y.flip(); C1 z = new C1(); ((C2)z).flip(); // Line A // Line B i. The statement on line A will generate a compiler error. Describe and explain the error. [3 marks] The compiler will complain that the object referenced by y has no flip method. This is because y is declared to be a reference to a C1 object. The compiler is unable to determine that the object which y references at this point will actually be a C2. ii. Write a revised version of line A, which achieves the desired effect of invoking the flip method on the object referenced by y. You should not make explicit mention of x. ((C2) y).flip(); iii. The statement on line B has a problem too. Explain what this is and describe how it will become apparent to the programmer. [3 marks] The object referenced by z cannot be cast to C2 because it was constructed as a C1 object (and C1 is a superclass of C2). The compiler cannot detect this error. The JVM will throw a ClassCastException when the statement is executed.
Question 5 (a) Construct finite state machines with the input alphabet {0, 1 that: i. Accept exactly those strings in which every 0 is immediately followed by at least one 1. The empty string should be accepted.
1 0 A B 1
ii. Accept exactly those strings containing just 0s and 1s in which there are never two consecutive 1s. The empty string should be accepted. [3 marks]
0 1 A B 0 1 C 0,1
(b) Can a finite state machine accept exactly the following sets of strings? Write yes in the box if so and no otherwise. i. All strings of 0s and 1s containing exactly three more 0s than 1s. no [1 mark] ii. All strings of 0s and 1s containing at least three more 0s than 1s. no [1 mark] (c) Write a regular expression that describes all strings containing just 0s and 1s in which there are never two consecutive 1s (the same set as in part (a)(ii) above). [3 marks] (0 10) (0 10) 1
Question 6 (a) What operations take place when a Java method with parameters in invoked? Comment on the relationship between the formal and actual parameters at the end of the invocation. [3 marks] Firstly the actual parameter expressions are evaluated in left-to-right order to give the values that are to be passed to the method. The formal parameters are given these initial values and the method body executed. If the formal parameter variables are updated in the method body, this change is not reflected in the actual parameters that were used for this invocation.. (b) Consider the following Java program. class Params { static void printinner(string s) { s = s + "!"; System.out.println(s); static void printmiddle(string s) { s = s + "!"; System.out.println(s); printinner(s); System.out.println(s); static void printouter(string s) { System.out.println(s); printmiddle(s); System.out.println(s); public static void main(string[] args) { printouter("hello"); What output does the program produce? [5 marks] Hello Hello! Hello!! Hello! Hello (c) What does it mean for a Java method to be marked as static? Are there any consequences for what code can appear in the method s body? All arguments to a static method are passed explicitly as actual parameters: a static method is not invoked on an object as a dynamic method is. A consequence is that it is not appropriate in a static method body to use fieldnames or invoke methods that implicitly or explicitly refer to the this argument of dynamic methods.
Question 7 Recall the selection sort algorithm for sorting an array of n integers: for (int i = 0; i <= n - 2; i++) { // Comment A int smallest = i; for (int j = i + 1; j <= n - 1; j++) if (A[j] < A[smallest]) smallest = j; // Comment B int temp = A[smallest]; A[smallest] = A[i]; A[i] = temp; (a) Suggest text for Comment A that concisely explains the effect of executing lines 3 5. Looks for the smallest element among A[i] to A[n-1] and records its location in the variable smallest. (b) Suggest text for Comment B that concisely explains the effect of executing lines 7 9. [1 mark] Swaps the contents of array elements A[i] and A[smallest]. (c) Suppose n = 6 and the array A is initialised to 4 9 6 1 3 8 Sketch the contents of array A after each iteration of the for-loop over i. [5 marks] After iteration 1: 1 9 6 4 3 8 After iteration 2: 1 3 6 4 9 8 After iteration 3: 1 3 4 6 9 8 After iteration 4: 1 3 4 6 9 8 After iteration 5: 1 3 4 6 8 9 (d) What is the worst case run time (as a big-oh expression in terms of n) for sorting n elements using selection sort? O(n 2 )
Question 8 (a) For each of the following pairs of formulas give a truth-value assignment at which the formulas have different truth values. i. P Q and P Q P f, Q t or P t, Q f [1 mark] ii. P Q and Q P P f, Q t or P t, Q f [1 mark] iii. P Q and P Q Only P f, Q t [1 mark] (b) i. Using the algebraic laws of boolean logic and a chain of equivalences argument, simplify the logical expression (P Q) P. writing each step of the simplification on a separate line. (P Q) P ( P Q) P ( Q P ) P Q ( P P ) Q t t ii. Is this expression a tautology? Explain. [1 mark] Yes, because it is (equivalent to) true for all truth values of P and Q. (c) i. Write a boolean-valued Java expression that evaluates to true when a Java variable x of type int[] is an array of 2 equal integers, and evaluates to false for all other possible values of x. Your solution should contain at least one strict or conditional logical operator. x!= null && x.length = 2 && x[0] == x[1] ii. Does it matter whether the logical operator(s) you use in your solution are strict or conditional? Discuss. Both must be conditional. If the left-hand one is not, the evaluation of x.length raises an exception when x is null. If the right-hand one is not, the evaluation of one of the array index expressions will raise an exception when x is an array of length 0 or 1.
Question 9 (a) Consider the recursive method public static int f(int i) { int r; if (i == 0) r = 1; else if (i % 2 == 0) r = f(i - 2) + f(i - 1); else r = 2 * f(i - 1); System.out.print(r + " "); return r; 1 1 2 3 6 One approach is to read values off a call tree that has call edges annotated with return values. What is printed out if f(3) is evaluated? Show your working clearly. [4 marks] (b) In Java, each method invocation is associated with a distinct activation record. What kind of information is held in an activation record? Values of arguments and local variables. Position in method code to resume at after return of method call. (c) Complete the code below for a method calculator which should read down an input stack a of ints, interpreting each as either data or an instruction. A non-negative element should be interpreted as data and should be inserted on the top of the computation stack s. A negative element should be interpreted as an instruction to replace the top two integers on the stack with their sum. The method should return the top value on the computation stack when the input stack is empty. [4 marks] public static int calculator (intstack a) { intstack s; while (!a.isempty()) { if (a.top() >= 0) s.push(a.pop()); else s.push(s.pop() + s.pop()); return s.top(); For example, if the input stack holds values 1, 2, 1, 3, 1 top-to-bottom, calculator should return (1 + 2) + 3 = 6. Assume intstack supports the following standard stack methods: public boolean isempty() public int pop() public int top() public void push(int i) and assume sum instructions are only included in the input stack when they are sensible.
Question 10 (a) Consider the following implementation of a variable-length integer array class. public class intarraylist { // Represents the array a[0]... a[size - 1] private int[] a; private int size; // Always 0 <= size < a.length... i. Write a method addlast() which takes an int value as argument and adds it to the end of the intarraylist object it is invoked on, providing there is space in the internal array. The method should return a boolean value, true just when the add is successful. public boolean addlast(int i) { if (size >= a.length) return false; a[size++] = i; return true; ii. Describe how you could modify your implementation of addlast() so that it is successful even when the the internal array is initially full. [3 marks] If size < a.length, the method should add the argument value as before. If size == a.length, the method should first allocate a new array of say 2 times the current size of a, copy the contents of a to this new array, and use this new array to replace a. (b) Complete the method below for checking whether a given object is a member of a given collection. Assume objects can be compared using an equals() method. Hint: use an iterator. [3 marks] public boolean member(object o, Collection c) { boolean r = false; Iterator i = c.iterator(); while (i.hasnext()) { r = r o.equals(i.next()); return r;
(c) Compare the time efficiency of accessing an element in a LinkedList object at a position referred to by an iterator and by an integer index. Access by iterator is in constant time. An access by integer index has to work from one end of the linked list, so worst case it can take time proportional to the list length.