CS211 About Prelim 2

The prelim is
7:30-9:00PM, Tuesday, 20 November 2001

The only reason for not taking it then is that you have a conflict with another evening prelim.
If this is the case, please let Gries know by Thursday, 15 November.

This file contains answers to the questions posed in handout "CS2aa About Prelim 2"

Questions on correctness of programs

1. An assertion is a true-false statement that is placed within a program to indicate that it is (or should be) true at that place. A Hoare triple has the form shown on the question: {precondition} statement {postcondition}. It has the meaning: execution of statement begun in a state in which the precondition is true is guaranteed to terminate with the postcondition true.

2. The precondition is the postcondition with every occurrence of x replaced by 2*x*y:  2*x*y+y < 64.

3. See the handout on correctness.

4. The first four algorithms are given in the handout on correctness. Here's (e)
The algorithm stores a^b in z, for b>= 0

    // {b >= 0}
    int x= a; int y= b;
    // {invariant: y>=0 and z*x^y = a^b }
    // {bound function: log y }
    while (y >= 0) {
        if (y%2 == 0) {x= x*x; y= y/2; }
        else                 { z= z*x; y= y-1; }
    }
    // {postcondition: z= a^b }

5.
(a)  i= h+1; x= 0;
      while (i  != k) {
          if (b[i] != b[i-1])  x= x+1;
          i= i+1;
      }

(b) j= k; x= 0;
     while (h != j) {
         j= j-1;
         if (b[j] = 0) x= x+1;
     }

(c) b= 1;
     while (2*b <= n) {
         b= 2*b;
     }

(d) p= b;
     while (p != null  &&  !p.element.equals(v))
        {  p= p.next; }

(e) p= h; q:= p; t= n;
    while (q != t) {
        if (b[q] is red) { Swap b[p] and b[q]; p= p+1; q= q+1; }
      else if (b[q] is white) { q= q+1; }
      else {  Swap b[q] and b[t]; t= t-1;}
      }

(f) Precondition: true
     Postcondition: 1 <= n <= 1000 and
                             pi is the sum of the first n terms of the sum  and
                             x = term n  and  abs(x) < 0.00001.
     Invariant:         1 <= n <= 1000 and
                             pi is the sum of the first n terms of the sum  and
                             x = term n
     Bound function: 1000 - n

     int n= 1;
     double pi= 4;
    double x= 1;
     while (n != 1000 && Math.abs(x) >= 0.00001) {
         n= n+1;
         x= 4/(2*n-1);
         if (n%2 == 0) x= -x;
         pi= pi + x;
     }

 (g) We did this one in some recitation handout.
 
 

Questions on older material (classes, subclasses, interfaces, exceptions)

1. A name m is overloaded if two methods with different signatures have name m; overloading can also occur if a variable and a method have the same name. Overriding refers to redefining a method is a subclass that is defined in a superclass.
 

2. We don't have an answer yet.
 
 
 

  • Briefly describe the stack data structure and the two fundamental operations for manipulating a stack.  (Do not write full Java code.)  We can use a stack to evaluate an expression in postfix form.  Show the stack at each phase during the evaluation of the following postfix expression.  At the end of the algorithm, the result should be left on the stack.

  •  

     
     
     
     
     

            1 2 3 * 4 - 12 6 / 7 * + +
     

  • a) In the class below, insert a static procedure that appends to a linked list L1 the elements of L2 --the last node of this list is changed to contain the name of the first cell of L2.  The  method does not return anything.  The lists are built using the class ListNode, given below.

  •  

     
     
     
     
     

    b) What is the asymptotic complexity of your algorithm, expressed as a function of n1 and n2, where n1 is the number of
    elements in L1 and n2 is the number of elements in L2?  Justify your answer (briefly).

    class LisNode {
            protected Object element;
            protected ListtNode next;

            // Constructor: an instance with element x and next field n
            public ListNode (Object x, ListNode n) {
                    datum = x;
                    next = n;
            }

            public Object getElement () {
                    return element;
            }

            public ListCell getNext () {
                    return next;
            }

            // Set this node's element to x
            public void setElement (Object x) {
                    datum = x;
            }

            // Change this next field to l
            public void setNext (ListNode l) {
                    next = l;
            }

            // Print this element together with the rest of the elements in this List
            public String toString () {
                    if (next == null) return element.toString();
                    return element.toString() + " " + next.toString();
            }
    }
     

  • (a) Java Nagila, a CS211 student, implemented a bunch of algorithms and came up with the following running times as a function of input size.  Using big-O notation, write down the simplest and most accurate expressions for the complexity of these algorithms.
  • (b) You have an algorithm that runs in time O(log n). Java Nagila claims to have found a better algorithm that runs in time O(log(n-1)).  Is either algorithm better than the other in an asymptotic sense?  Explain your answer briefly using the formal definition of big-O notation.

    (c) The following method returns the element number i of an integer list.

    What is the asymptotic time complexity of accessing the element m of a list using this method?  Express the complexity as a function of m and n, the length of the list.
     
     
  • Fill in the table below with the expected time for each operation. Use big-O notation. The operations are insert (place a new item in the data structure), find (test if a given item is in the data structure), getMin (return the value of the minimum item in the data structure and delete it from the data structure), and successor (given an item, return the successor of that item).

  •  
     
    Data Structure insert find getMin successor
    sorted array        
    unsorted array        
    balanced tree        
    hashtable        
    sorted linked list        
    unsorted linked list        
  • Where is the smallest element in a Binary Search Tree? The following picture represents a BST (Binary Search Tree).
  •              (22)
    
               /      \
    
           (14)        (25)
    
          /   \       /    \
    
       (11)   (16) (23)     (40)
    
                      \     /
    
                     (24) (32)
  • For each of the following problems, choose the best of the listed data structures and explain why your choice is best. Assume that the data set is going to be large unless otherwise indicated.  Where several operations are listed you should assume, unless stated otherwise, that the operations occur with about equal frequency.
  • You have a hash table of size m=11 and a (not very good) hash function h:

  •  

     
     
     

            h(x) = (sum of the values of the first and last letters of x) mod m

    where the value of a letter is its position in the alphabet (e.g., value(a)=1, value(b)=2, etc.). Here are some precomputed hash values:

     
    word ape bat bird carp dog hare ibex mud koala stork
    h 6 0 6 7 0 2 0 6 1 8

    Draw a picture of the resulting hashtable (using chaining) after inserting, in order, the following words: ibex, hare, ape, bat, koala, mud, dog, carp, stork. Which cells are looked at when trying to find bird?  What is the load factor (lambda) for the hash table?
     

  • The following questions refer to an implementation of an type with operations Insert, Delete, and isMember. These are the only operations, so for this problem it is not an advantage for a data structure to allow more operations.
  • The departmental phone number is 2557316. Show how the order of the digits changes as the digits are sorted using Quick

  • Sort, Insertion Sort, and Merge Sort. For Quick Sort, assume that the first item is used as the pivot item (this is not a
    good choice).
     
  • Consider the following sorting methods: Insertion Sort, Merge Sort, and Quick Sort.

  •  

     
     
     

         a.What is the running time for each method when all the keys are equal?
         b.When the keys are in order?
         c.When the keys are in reverse order?
     

  • Write a method that takes as input a binary search tree, T, and two keys k1 and k2, which are ordered so that k1 <= k2, and prints all elements X in the tree such that k1 <= key(X) <= k2. You may assume that the keys are of type Comparable. Your program should run in time O(K + log N), where K is the number of keys printed.

  •  
  • Give a recursive algorithm for making change with the smallest number of coins. The input to your method is an integer array coins[] containing the possible values for the coins and an int that is the change needed. The output should be an array indicating the number of each coin needed. So, if the input is coins[] = {1, 5, 10, 25} and amount = 55, then the output should be an array change[] = {0, 1, 0, 2}. Hint: For the recursive step, subtract the amount of one coin from the amount of change needed. Be careful to use the smallest number of coins in your solution.

  •  
  • Specify and a recursive method that determines whether a String s is

  • a palindrome.  A palindrom is a String that reads the same backward and forward.
     
  • Java does not allow multiple inheritance because two classes can define methods with the same signature that do completely different things.  Therefore, if a child class extends two such

  • classes, if it refers to one of these pre-existing methods in a super class, JAVA won't know which method to execute.  However, Java does allow a class to implement more than one interface.  Why don't interfaces have the same problem with method ambiguity that classes do?
     
  • Which of the following classes correctly implements the Enumeration interface? Explain what's wrong with the one(s) that don't.

  •  

     

    public class Num1 implements Enumeration {

        public Num1() { }

        public boolean hasMoreElements()
            { return true;  }

        public Object nextElement()
            { return "hello";  }
    }

    public class Num2 implements Enumeration {

        public Num2 { }

        private boolean hasMoreElements()
            { return true;  }

        private Object nextElement()
            { return "hello";  }

    }

    public class Num3 implements Enumeration{

        String[] x;
        int k = 0;

        public Num3() {
            x = new String[10];
            for (int i = 0; i < 10; i++)
            x[i] = "" + i;
         }

        public boolean hasMoreElements()
            { return (k < x.length);  }

        public Object nextElement()
            { return x[k++];  }

        public Object nextElement(int j)
            { return x[j];  }
    }
     

  • Write exactly one method that takes in an integer and throws two new exceptions (of type Exception) with messages "Too high!" and "Too low!".  If the value is out of the range 0..100 (inclusive), throw the appropriate exception.

  •  
  • Suppose method A calls method B, and method B calls method C, and C is defined to potentially throw an exception.  Can this exception be handled in method A?  If not, why?  If so, how?