Key to Sample CSE143 Midterm, Summer 2009 handout #21 1. Method Call Output Produced ----------------------------------------------- mystery(3, 3); =3= mystery(5, 1); * mystery(1, 5); 5 4 =3= 2 1 mystery(2, 7); 7 6 5 * 4 3 2 mystery(1, 8); 8 7 6 5 * 4 3 2 1 2. One possible solution appears below. public String repeat(String s, int n) { if (n < 0) throw new IllegalArgumentException(); else if (n == 0) return ""; else if (n == 1) return s; else if (n % 2 == 0) { String temp = repeat(s, n / 2); return temp + temp; // alternative without temp: return repeat(s + s, n / 2); } else return s + repeat(s, n - 1); } 3. One possible solution appears below. public int maxAdjacentPairSum() { if (front == null || front.next == null) return 0; else { ListNode current = front; int max = front.data + front.next.data; while (current.next != null) { int next = current.data + current.next.data; if (next > max) max = next; current = current.next; } return max; } } 4. Statement Output ------------------------------------------------------------ var1.method1(); Blue 1/Blue 2 var2.method1(); Green 1 var3.method1(); compiler error var4.method1(); Green 1 var1.method2(); Blue 2 var2.method2(); Red 2/Blue 2 var3.method2(); compiler error var4.method2(); Red 2/Blue 2 var1.method3(); compiler error var2.method3(); Green 3 var3.method3(); compiler error var4.method3(); compiler error ((Blue)var3).method1(); Blue 1/White 2 ((Red)var3).method2(); White 2 ((White)var3).method3(); White 3 ((White)var4).method3(); runtime error ((Green)var5).method3(); runtime error ((Red)var5).method1(); Blue 1/Red 2/Blue 2 ((Blue)var6).method3(); compiler error ((Green)var6).method3(); runtime error 5. One possible solution appears below. public void switchPairs(Stack<Integer> s) { Queue<Integer> q = new LinkedQueue<Integer>(); while (!s.isEmpty()) q.enqueue(s.pop()); while (!q.isEmpty()) s.push(q.dequeue()); while (!s.isEmpty()) q.enqueue(s.pop()); while (q.size() > 1) { int n1 = q.dequeue(); int n2 = q.dequeue(); s.push(n2); s.push(n1); } if (!q.isEmpty()) s.push(q.dequeue()); } 6. One possible solution appears below. public int maxCount() { if (size == 0) { return 0; } else { int max = 1; int count = 1; for (int i = 1; i < size; i++) if (elementData[i] == elementData[i - 1]) { count++; if (count > max) { max = count; } } else count = 1; return max; } }
Stuart Reges