Faculty of Science FINAL EXAMINATION STUDENT NAME: ID:

advertisement
Faculty of Science
FINAL EXAMINATION
COMPUTER SCIENCE COMP 250
INTRODUCTION TO COMPUTER SCIENCE
Examiner:
Prof. Michael Langer
Associate Examiner: Prof. Paul Kry
Dec. 13, 2012
9 A.M. – 12 P.M.
STUDENT NAME:
ID:
Instructions:
The exam is 14 pages, including this cover page.
There are 10 questions, worth a total of 60 58 points.
Answer all questions on the exam question sheet.
An extra page is included at the end for sketching out solutions.
No calculators, notes, or books are allowed.
Question Points Grade
1
4
2
4
3
4
4
6
5
6
6
7
7
10 8
8
7
9
6
10
6
Total
60 58
1
COMP 250
1. (4 points)
(a) Fill in the missing code in the indicated region /*..*/ for the following method in a
Java ArrayList<T> class implementation. The method should remove and return the
list element at index i.
State any assumptions you make about the private fields of the class.
public T remove(int index){
T tmp;
if ((index >= 0) && (index < size)){
//
//
-------- SOLUTION BEGIN-----------------------assume a private field array[]
tmp = array[index];
for (int j=index; j < size-1; j++){
array[j] = array[j+1];
}
size--;
return tmp;
//
-------
SOLUTION END
/*
*
*/
// j == size-1 will give
// error if size==length
------------------------
}
else {
System.out.println("array index out of bounds");
return null;
}
}
GRADING: 2 points. Took off 0.5 for an off-by-one error in the upper index e.g. size
instead of size-1.. Took off 0.5 for forgetting to decrement the size field.
Many students relied on a get(i) and set(i) method rather than explicitly assuming an
underlying array. This was allowed.
(b) What is the O( ) and Ω( ) bound for this method? Briefly justify your answer.
SOLUTION/GRADING: 2 points. O(n) because worst case is that you have to shift
all the elements and so t(n) is proportional to n. Ω(1) because best case is that you are
removing the first element and so t(n) = const. 0.5 for each answer and justification.
2
COMP 250
2. (4 points)
Consider the following Java method.
LinkedList<String> mysteryMethod( LinkedList<String> list ){
String s1,s2;
LinkedList<String> list1 = new LinkedList<String>();
LinkedList<String> list2;
while (!list.isEmpty()){
s1 = list.removeFirst();
list1.add(s1);
list2 = new LinkedList<String>();
while (!list.isEmpty()){
s2 = list.removeFirst();
if (!s1.equals(s2)){
list2.add(s2);
}
}
list = list2;
}
return list1;
}
(a) The method takes a linked list of strings as input. What does the method compute ?
SOLUTION AND GRADING: 1 point. The method computes/returns a list of
strings with all duplicates removed.
(b) Give the O( ) bound on the number of calls to the equals() method, that is, the number
of String comparisons required by the method. Justify your answer.
SOLUTION AND GRADING: In the worst case, all the strings are different i.e. no
duplicates. In that case, we need n passes through the while loop and pass i takes time
proportional to n − i. So, t(n) ≈ n + (n − 1) + (n − 2) + ... + 2 + 1 = n(n+1)
which is
2
2
O(n ). 0.5 points for the solution and 1 point for explanation.
(c) Same as (b), but give the Ω( ) bound. Justify your answer.
SOLUTION AND GRADING: In the best case, all the elements are the same and
so only one pass is done, and t(n) is proportional to n and so t(n) is Ω(n). 0.5 points for
the solution and 1 point for explanation.
3
COMP 250
3. (4 points)
(a) Give the formal definition for “t(n) is O(g(n))”.
SOLUTION AND GRADING: “t(n) is O(g(n))” means that there exist two positive
constants c, n0 such that t(n) < cg(n) whenever n ≥ n0 . 1 point.
(b) Let t(n) be such that t(n) = 1 when n is odd and t(n) = 1 + 2n when n is even, i.e.
n
t(n)
1
1
2
5
3
1
4
9
5
1
6
13
7
1
8 ...
17 ...
Underline the asymptotic bounds below for which we can say “t(n) is
O(1)
O(log n)
O(n)
O(n2 )
Ω(1)
Ω(log n)
”.
Ω(n)
Ω(n2 )
You do not need to justify your answers.
SOLUTION AND GRADING: 3 points. 1 point for each correct answer. Minus 1 for
each incorrect answer i.e. underlying a bound that isn’t a bound.
4
COMP 250
4. (6 points)
(a) Below left is the recursive algorithm for power(x,n). Fill in the missing code on the right
of a non-recursive version of the same algorithm which uses a stack instead of recursion.
RECURSIVE
power(x,n) {
if (n == 0)
return 1
else{
tmp = power(x, n/2)
if (n % 2 == 0)
return tmp*tmp
else
return tmp*tmp*x
}
}
NON-RECURSIVE
power(x,n) {
tmp = 1
s = empty stack
while ( n > 0 ){
//
s.push( n % 2 )
//
n = n/2
}
while ( ! s.isEmpty()
//
i = s.pop()
//
if (i == 1) //
//
tmp = tmp *
//
else
//
tmp = tmp *
}
return tmp;
}
){
odd
tmp * x
tmp
SOLUTION AND GRADING: 3 points. There are several ways to do it. 1 point for
pushing something that can be used to say whether to square the result of the recursive
call or whether to square it and multiply by x. 1 point for dividing n by 2 in the first
while loop. 1 point for the case analysis on updating temp in the second while loop.
We gave 1 point only if you gave a O(n) algorithm since its a different algorithm.
(b) For the recursive algorithm, write a recurrence relation for the upper bound on the number
of multiplications needed to compute power(x,n), and solve the recurrence i.e. solve for
the upper bound. Use the other side of the page, if necessary.
SOLUTION AND GRADING:
t(n) <=
<=
<=
t(n/2) + 2
t(n/4) + 2 + 2
2 log n
0.5 for "1" instead of "2"
3 points: one for each line above, i.e. initial recurrence, back substitution and the final
answer.
5
COMP 250
5. (6 points)
Consider the binary tree:
h
/
p
\
w
/
d
\
m
/ \
f y
(a) What is the order of nodes visited in a pre-order traversal?
SOLUTION AND GRADING: 1 point. h p w d m f y
(b) What is the order of nodes visited in an in-order traversal?
SOLUTION AND GRADING: 1 point. p d w h f m y
(c) What is the order of nodes visited in a post-order traversal?
SOLUTION AND GRADING: 1 point. d w p f y m h
(d) Transform this binary tree into a binary search tree of height 2, defined by the natural
ordering on characters.
SOLUTION AND GRADING: 2 points.
m
/
f
/ \
d
h
\
w
/ \
p y
(e) Show the result of removing m from your binary search tree.
SOLUTION AND GRADING: 1 point.
p
/
f
/ \
d
h
\
w
or
\
y
6
h
/ \
f
w
/
/ \
d
p y
COMP 250
6. (7 points)
(a) Consider an list of keys (h, p, m, w, f, y, d). Assuming this is the initial ordering
of the keys in an array implementation, use the fast buildHeap() algorithm, i.e.
for (k = n/2; k >= 0; k--)
downHeap( a, n, k )
to build a (min)-heap from these keys. Recall that downHeap() assumes node k is the
parent of two heaps, and adjusts the tree so that node k becomes the root of a heap.
SOLUTION AND GRADING: 2 points for this particular heap. 1 point for any
other heap.
d
/ \
f
h
/\
/ \
w p y m
(d f h w p y m)
(b) Show the result of removing the minimum element from your heap in (a).
SOLUTION AND GRADING: 1 point. If student gets (a) wrong then check solution
for (b) relative to student’s solution for (a).
f
/ \
m
h
/\
/
w p y
f m h w p y
(c) Give O() and Ω() bounds for the following heap operations, as a function of the number
n of keys in the heap. Briefly justify your answers.
• removeMin(), which returns the minimum key;
SOLUTION AND GRADING: 2 × 0.5 for answers, 2 × 0.5 for justification.
O(log n) since you have to downHeap the height of the tree.
Ω(1) – the last node in the array which is put into the root might need to be
downHeaped only one level (on the other branch).
• remove(key), which removes a given key if it is present in the heap. (If there are
multiple copies of the key then this method just removes one copy.)
SOLUTION AND GRADING: 2 × 0.5 for answers, 2 × 0.5 for justification.
O(n) - to find the key in the heap using the standard array implementation, you
need a linear search.
Ω(1) - best case is the key you are looking is the first one in the array, which reduces
to solution for removeMin().
7
COMP 250
7. (10 points
8 points)
Suppose the classes below are all in the same package. See questions on next page.
public class Sharer{
int
sum;
String ID;
Sharer other;
public Sharer(String ID, int sum){ this.ID = ID;
// give half, keep half
void share(int n){ other.sum += n/2;
this.sum = sum; }
this.sum += n - n/2;
}
public String toString(){ return ID + " " + sum + " "; }
}
class Giver extends Sharer{
public Giver(String ID, int sum) { super(ID, sum); }
void share(int n) {
other.sum += n;
this.sum
-= n;
}
}
class Taker extends Sharer{
public Taker(String ID, int sum) {
void share(int n) {
super(ID, sum);
other.sum -= n;
this.sum
}
+= n;
}
}
public class Test {
public static
Sharer a
Sharer b
Sharer c
void main(String[] args) {
= new Giver("Geoff", 10);
= new Taker("Tina", 7);
= new Taker("Ted", 15);
a.other = b;
a.share(2);
b.other = c;
b.share(4);
c.other = a;
c.share(7);
System.out.println( a.toString() +
}
}
8
b.toString() + c.toString());
COMP 250
(a) What is the output when the Test class is run?
SOLUTION AND GRADING: 3 points.
Geoff 1
Tim 13
Ted 18
(b) Suppose we were re-define the visibility of the three fields of Sharer to be private so
that the Giver and Taker no longer have access to these fields.
Rewrite the methods of Sharer, Giver, and Taker to be consistent with this new definition. Only re-write methods that change. You can rewrite the methods next to the
code on the previous page and/or here.
SOLUTION AND GRADING: I was originally planning for (b) to have 7 points. However, the wording was not so clear: during the exam, many students asked whether they can
add getters and setters. We are therefore reduced (b) to 5 points.
// in the Sharer class
(1 point)
Sharer getOther(){ return
this.other; }
void
setOther(Sharer other){ this.other = other; }
int
getSum(){
void
setSum(int n){
return
// in the Giver class
this.sum;
this.sum
=
}
n;
}
(2 points)
void share(int n) {
this.getOther().setSum( this.getOther.getSum() + n );
this.setSum( this.getSum() - n ); }
}
//
in the Taker class
(2 points)
void share(int n) {
this.getOther().setSum( this.getSum() - n);
this.setSum( this.getSum() + n );
}
9
COMP 250
8. (7 points)
Consider the GUI that is defined by the following class.
class MyPanel extends JPanel{
int fontSize = 12;
JButton button;
JLabel myLabel;
MyPanel(){
button = new JButton();
ButtonListener listener = new ButtonListener();
button.addActionListener( listener );
myLabel = new JLabel("my button");
button.add(myLabel);
setLayout( new FlowLayout());
add(button);
}
private class ButtonListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button){
myLabel.setFont( new Font("Times", Font.BOLD, fontSize++ ));
}
}
}
}
(a) Briefly describe the interface: What does the user see? What does the user do, and what
does the user see as the result ?
SOLUTION AND GRADING:
1 point. The user sees a button with a label “my button”. The user moves the mouse
to the button and then clicks on the button. The font changes to Times/Bold and size
increases. Subsequent button presses increase font size.
10
COMP 250
(b) What are the objects produced by this GUI and by the user’s actions?
SOLUTION AND GRADING: 2 points. There are many objects: JButton, JLabel,
MyPanel, ActionEvent, ButtonListener, Font, FlowLayout. We have 0.5 points for each,
up to a maximum of 4.
(c) Summarize the steps that occurs internally in the program, that lead from the user’s
action to the change that the user sees on the screen? In particular, your answer should
discuss the relationships between the objects listed in (b).
SOLUTION AND GRADING: 4 points.
We were looking for an understanding of the ActionEvent object and its relationship to
the ActionListener. If you hardly mentioned ActionEvent, then you did not do well
on this question. Here are the main steps we were looking for:
i. When user clicks on the button, an ActionEvent object is generated. (It is put into
an event queue and then eventually removed and processed.)
ii. When the ActionEvent object is processed, its source field is checked. This field
references the JButton object.
iii. The list of listeners (that have been added to that JButton is checked; one of them
is the ButtonListener object.
iv. The ButtonListener object’s actionPerformed method is invoked with the ActionEvent
passed to it as a parameter. The actionPerformed() method increases the font size
of the JLabel object.
11
COMP 250
9. (6 points)
(a) Consider a hash table with (key, value) pairs,
(11, sleep), (42, bed), (9, frog), (61, dog), (17, pizza), (21, pen)
and hash function
h(k) = k mod 11.
Draw the hash table.
0
1
2
3
4
5
6
7
8
9
10
- (11, sleep)
- (61, dog),
(17, pizza)
- (42, bed),
- (21, pen)
(9, frog)
SOLUTION AND GRADING: 2 points. They must put the (original) keys and
values. Must have slots 0, .. 10.
(b) Consider a hash table with capacity of m buckets, and n entries i.e. n (key, value) pairs.
• Give a O() bound for the method contains(K key) which examines whether there
is an entry in the hash table with that key. Justify your answer, and state your
assumptions.
SOLUTION AND GRADING: 2 points. O(1), since the purpose of a hash table
is that it is supposed to be big enough and with a good hash function to give constant
time access.
Give 1 point for saying O(n) and justifying it (but not mentioning that the purpose
of a hashtable is to give O(1) access).
• Give a O() bound for the method contains(V value) which examines whether
there is a particular value in the hash table. Justify your answer, and state your
assumptions.
SOLUTION AND GRADING: 2 points. O(m + n), since we have to go through
every bucket and every entry in each bucket to find the value. Give 1 point for O(m)
or O(n).
12
COMP 250
10. (6 points)
The figure below shows a set of rectangles whose overlap relationships can be represented
using a directed graph, as follows. Each rectangle is represented in the graph by one vertex,
and there is a directed edge in the graph whenever part of one rectangle lies on top of another
rectangle. For the example below, there is an edge from G to H, but not from H to G and there
are no edges between A and B since these rectangles do not overlap at all.
G
F
C
A
H
E
D
B
(a) Give the adjacency list for this graph, such that the vertices are ordered alphabetically.
Note that this ordering implies that there is a unique answer.
SOLUTION AND GRADING: 2 points. (1 point for small mistakes)
A
B
C
D
E
F
G
H
-
D,
D
G
C,
B
B,
B,
F
E
H
C
H
(b) Using the adjacency list in (a), give the ordering of vertices visited in a breadth first
traversal of the graph, starting from vertex A.
SOLUTION AND GRADING: A D E C H B G F
2 points. If (a) was incorrect,
we check solution for (b) relative to your solution for (a).
(c) Using (a), give the ordering of vertices visited in a pre-order (depth first) traversal, again
starting from A.
SOLUTION AND GRADING: A D C G B H F E
2 points. If (a) was incorrect,
we check solution for (b) relative to your solution for (a).
13
Download