Key to CSE143 Midterm, Fall 2008 handout #21
1. Method Call Value Returned
-----------------------------------------------
mystery(7); 8
mystery(42); 53
mystery(385); 496
mystery(-790); -801
mystery(89294); 90305
2. One possible solution appears below.
public int digitMatch(int x, int y) {
if (x < 0 || y < 0)
throw new IllegalArgumentException();
else if (x < 10 || y < 10) {
if (x % 10 == y % 10)
return 1;
else
return 0;
} else if (x % 10 == y % 10)
return 1 + digitMatch(x / 10, y / 10);
else
return digitMatch(x / 10, y / 10);
}
3. One possible solution appears below.
public boolean isSortedByN(int n) {
if (n <= 0)
throw new IllegalArgumentException();
ListNode current1 = front;
ListNode current2 = front;
while (current2 != null && n > 0) {
current2 = current2.next;
n--;
}
while (current2 != null) {
if (current1.data > current2.data)
return false;
current1 = current1.next;
current2 = current2.next;
}
return true;
}
4. Statement Output
------------------------------------------------------------
var1.method2(); Table 2/Chair 2
var2.method2(); Table 2/Chair 2
var3.method2(); Table 2/Chair 2
var4.method2(); Lamp 2
var5.method2(); Table 2/Chair 2
var6.method2(); compiler error
var1.method1(); Table 1
var2.method1(); compiler error
var3.method1(); Couch 1
var4.method1(); compiler error
var1.method3(); Table 3/Table 1
var2.method3(); compiler error
var3.method3(); Table 3/Couch 1
((Lamp)var4).method1(); Lamp 1
((Lamp)var2).method1(); runtime error
((Table)var5).method1(); Couch 1
((Couch)var1).method1(); runtime error
((Chair)var6).method2(); Chair 2
((Couch)var5).method3(); Table 3/Couch 1
((Table)var5).method3(); Table 3/Couch 1
5. One possible solution appears below.
public void compressDuplicates(Stack s) {
Queue q = new LinkedQueue();
while (!s.isEmpty())
q.enqueue(s.pop());
while (!q.isEmpty())
s.push(q.dequeue());
while (!s.isEmpty())
q.enqueue(s.pop());
if (!q.isEmpty()) {
int last = q.dequeue();
int count = 1;
while (!q.isEmpty()) {
int next = q.dequeue();
if (next == last)
count++;
else {
s.push(count);
s.push(last);
count = 1;
last = next;
}
}
s.push(count);
s.push(last);
}
}
6. One possible solution appears below.
public boolean isConsecutive() {
for (int i = 0; i < size - 1; i++)
if (elementData[i + 1] != elementData[i] + 1)
return false;
return true;
}
Stuart Reges
Last modified: Fri Sep 16 16:16:07 PDT 2011