Grader Use Only: #1 CMSC132 Fall 2005 Final Exam Key First Name: _______________________ Last Name: _______________________ #2 (7) #3 (8) #4 (13) #5 (9) #6 (16) #7 (9) #8 (7) #9 (8) #10 (8) Student ID: _______________________ Total Section time ___________ Honors TA: _____________________ I pledge on my honor that I have not given or received any unauthorized assistance on this examination. Your signature: _____________________________________________________________ General Rules (Read): a. b. c. d. e. This exam is closed book and closed notes. If you have a question, please raise your hand. Total point value is 100 points. Answer True/False questions by circling the T or F at the end of the question. Answer multiple-choice questions by circling the letter (e.g., a, b) at the front of each choice. f. Answer essay questions concisely using 1 or 2 sentences. Longer answers are not necessary and are discouraged. g. WRITE NEATLY. If we cannot understand your answer, we will not grade it (i.e., 0 credit). h. Honors section questions only count for credit for students in the honors section. 1 (15) (100) (8) Problem 1 (15 pts) Software Engineering & Object-Oriented Design a. (1 pt) The Waterfall model is reasonable for both small and large projects. T or F b. (1 pt) The Waterfall model, Unified model, and Rapid Prototyping are intended to be models of what? (Hint: Provide a 3-word answer. You get 0 points for providing definitions of each model) Software life cycle c. (1 pt) Define data abstraction. Hiding implementation details of data d. (8 pts) Given the following problem description, produce an object-oriented solution and answer the questions below. Design a software system for a bookstore that keeps an inventory of two types of books: traditional books and books on CD. Books on CD may also contain music. The bookstore purchases books from publishers and sets a price for each book. Customers can purchase books from the bookstore, using either cash or a credit card. The bookstore keeps track of which books it has its inventory, and the books purchased by each customer. i. What are the objects in your object-oriented solution? Store, Book, NormalBook, CDBook, Customer (NormalBook is optional) ii. What are the interactions between objects in your object-oriented solution? BookstorePurchaseBook(FromPublisher), SetPrice, CustomerPurchaseBook(FromBookstore) iii. Which objects “have” other objects? (Also list target object) Store has Book, Store has Customer, (Customer has Book is optional) iv. Which objects “use” other objects? (Also list target object) Customer uses Book (is optional if Customer has book) v. Which objects “are” other objects? (Also list target object) NormalBook is Book, CDBook is Book (NormalBook is optional) e. (4 pts) Given the following Java code, draw its UML class diagram. public class Button { RemoteControl public String operation; controlButton : Button[ ] public double frequency; * } dvd : DVD public class DVD { allOnButton : AllOnButton public void onOff() { // … } activateButton( String, String ) : void public void play() { // … } } public class AllOnButton extends Button { 1 1 public int currentValue; DVD } public class RemoteControl { public Button[ ] controlButtons; onOff( ) : void public DVD dvd; play( ) : void public AllOnButton allOnButton; public void activateButtonOn(String operation, String deviceName) { //... } } 2 Button operation : String frequency : double AllOnButton currentValue : int Problem 2 (7 pts) Algorithm Complexity a. (3 pts) Calculate the asymptotic complexity of the code snippets below (using big-O notation) with respect to the problem size n. i. for (int i=0; i<n/2; i++) { f(n) = O( n ) for (int k=0; k<20; k++) { for (int j=0; j<30; j++) { // ... } } } ii. for (int i=n/2; i<=n; i++) { f(n) = O( n log(n) log(n) ) for (int j=1; j<=n; j=j*2) { for (int k=1; k<=n; k=k*2) { // ... } } } iii. for (int i=1; i<=100; i++) { f(n) = O( 1 ) // ... } b. (2 pts) List the following big-O expressions in order of asymptotic complexity (with the lowest complexity first) O(nlog(n)) O(1) O(log(n)) O(2^n) O(n) O(1), O(log(n)), O(n), O(nlog(n)), O(2^n) c. (2 pts) How can asymptotic complexity be analyzed for recursive algorithms? Using recurrence relations Problem 3 (8 pts) Data Structures and Recursion a. (1 pt) Elements in a map have exactly 1 successor. T or F b. (1 pt) A base case is optional for some recursive problems. T or F c. (6 pts) Given the following Java class definition for a binary tree, write a recursive method named numLeafNodes that determines the number of leaf nodes in the binary tree. Remember that leaf nodes are nodes with no children. Assume “left” and “right” have the value “null” if no subtree is present. You may use helper functions. Class Node { Object myValue; Node left; Node right; } Class Tree { Node root; // root node in tree int numLeafNodes( ) { // return number of leaf nodes in tree return countLeaf( root ); } int countLeaf(Node n) { if (n == null) return 0; int L = countLeaf(n.left); int R = countLeaf(n.right); if (n.left == null) && (n.right == null)) return 1; return L+R; } 3 Problem 4 (13 pts) Graph Algorithms a. b. c. d. (1 pt) Every cycle is a path. (1 pt) Every graph has a unique minimum spanning tree. (1 pt) You can implement a Depth First Traversal using a Queue. (10 pts) Consider the following graph. T or F T or F T or F 10 10 4 S B D 2 2 1 3 A 6 C 6 E 8 7 i. (2 pts) List the set of nodes visited (in the order first visited) while performing a Depth First Search starting at B. B,A,C,E,D or B,C,E,D,A or B,D,A,C,E or B,D,C,E,A or BCEAD (C,E,D always immediately after A unless already visited, E,D always after C unless already visited) ii. (2 pts) List the set of nodes visited (in the order first visited) while performing a Breadth First Search starting at B. B,A,C,D,E or B,A,D,C,E or B,C,A,D,E or B,C,D,A,E (E is always last) iii. (2 pts) List the first edge rejected by Kruskal’s minimal spanning tree algorithm (you can treat all edges as undirected edges for this problem) (A,C) or (D,E) iv. (4 pts) Show the entries in the following table after adding the first 3 nodes (S & 2 other nodes) when applying Djikstra’s single source shortest path algorithm starting at S. S LowestCost 0 Predecessor none A B C D E 2 10 8 10 16 S S A S C 4 Problem 5 (9 pts) Compression and Huffman Codes a. (1 pt) The compression factor associated with the Huffman encoding is affected by how 0’s and 1’s are assigned to a Huffman tree. b. (4 pts) Consider the following Huffman tree. H T 0 1 M K Z 0 0 1 1 0 1 i. (2 pts) Decode the sequence “1001000” ii. (2 pts) Encode the string “MTZ” KMH 0100111 c. (4 pts) Create a Huffman tree for the following nodes A B B C D C A D 5 T or F Problem 6 (16 pts) Multithreading and Synchronization a. b. c. d. (1 pt) Excessive use of synchronization mechanisms can reduce performance. T or F (1 pt) A Java object can be assigned two locks. T or F (1 pt) A program with data races will produce different results each time it is run. T or F (9 pts) Given the following diagram of states a thread can assume, draw all possible transitions between states, and list one possible cause for each transition. notify, notifyAll, IO complete, sleep expired, join complete runnable start yield, time slice scheduler new running blocked IO, sleep, wait, join terminate dead e. (4 pts) Consider the following code for a multithreaded Cashier class: public class Cashier { private static MyQueue clientQueue = new MyQueue( ); // same Queue for all cashiers … public void doWork() { // work on register, then work with client if one is in the Queue int queueLength; workOnRegister( ); // do some work without client queueLength = clientQueue.size(); if (queueLength > 0) { Object client = clientQueue.dequeue(); workWithClient( client ); } } } 6 // do some work with client i. (1 pts) Why are data races possible if two Cashier objects invoke doWork( ) simultaneously? Because they access the same shared clientQueue object ii. (3 pts) Change the doWork() method so that multiple Cashier objects can safely invoke the doWork( ) method simultaneously. Maximize the amount of parallelism exploited by ensuring multiple Cashiers can invoke workOnRegister( ) and workWithClient( ) simultaneously. public void doWork() { // work on register, then work with client if one is in the Queue int queueLength; // your code here… workOnRegister( ); // do some work without client Object client = null; synchronize(clientQueue) { queueLength = clientQueue.size(); if (queueLength > 0) { client = clientQueue.dequeue(); } } if (client != null) workWithClient( client ); // do some work with client } Problem 7 (9 pts) Advanced Tree Data Structures a. (2 pt) What is the property that an AVL tree must maintain so that the tree is balanced? The height of left and right subtrees differ by at most 1 b. (1 pt) In a Red-black tree no leaf is twice as far from root as another leaf. T or F c. (2 pt) Consider the following binary search tree and then draw the tree that will result from doing a single right rotation around node 7. 5 7 5 2 7 2 8 6 6 8 d. (2 pts) Draw the 2-3 tree that will result from inserting the value 4 in the following tree. 8 28 4 15 33 43 7 e. (2 pts) Draw a standard trie to represent the strings in the set {boy, bat, bad} b a d o t y Problem 8 (7 pts) Java Language Features a. (2 pt) What is a shallow copy? A copy of an object with the same value in each field b. (1 pt) The default clone method creates a shallow copy of the object. T or F c. (2pt) What is a checked exception? Errors typical program should handle, used for operations prone to error d. (2 pts) Given the following Java code fragment using java.util.regex: Pattern p = Pattern.compile(“[a-z]+”); Matcher m = p.matcher(“12abc ab12c”); while (m.find()) { System.out.print(m.group() + “\n”); } What will be printed out when the code is executed? abc ab c (each on new line) Problem 9 (8 pts) Sorting, & Algorithm Strategies a. (1 pt) What is the worst case complexity of sorting using quicksort? O(n2) b. (2 pt) What can cause worst case behavior for quicksort? Picking min or max value in list for pivot (e.g., sorted list if always picking 1st element as pivot) c. (1 pt) What is the average case complexity of sorting using bucket sort? d. (2 pt) Why may we want to use a stable sort? O(n) Sorting each component in a radix sort e. (1 pt) Which algorithm strategy allows us to efficiently compute the minimal spanning tree of a graph? Greedy f. (1 pt) Which algorithm strategy allows us to efficiently compute the shortest path between two nodes in a graph? Dynamic programming (+greedy optional, greedy alone is incorrect) 8 Problem 10 (8 pts) Design Patterns a. (2 pt) Why do programmers use design patterns? Benefit from design of experienced programmers b. (4 pts) Based on the information provided by the following interface and classes implement a class called ComputerDecorator which implements the decorator design pattern. public interface Computer { public int cost(); } public class Laptop implements Computer { public int cost() { return 500; } } /* Class using the decorator you are expected to write */ public class withDVDUnit extends ComputerDecorator { public int cost() {return c.cost() + 100; } } public class ComputerDecorator implements Computer { private Computer c; public ComputerDecorator( Computer c ) { this.c = c; } public int cost( ) { return c.cost( ); } } c. (2 pt) Use the withDVDUnit decorator to create a Laptop computer with DVDUnit that costs 600. Computer myDVDLaptop = new withDVDUnit ( new Laptop( ) ) ; Problems for Honors Section (8 pts) a. (2 pts) What is Catch or Declare? Java compiler requires: catch and handle exception in method, OR declare method can throw exception, force calling function to catch or declare exception in turn b. (2 pts) Explain how multithreaded Java code can improve performance even for a computer with a single processor Perform useful work in other threads when thread is waiting (e.g., for disk, network) c. (2 pts) Given the following Java code fragment using java.util.regex: Pattern p = Pattern.compile(“[a-z][0-9]+”); Matcher m = p.matcher(“12abc ab12c”); while (m.find()) { System.out.print(m.group() + “\n”); } What will be printed out when the code is executed? 12c d. (2 pts) Why is it difficult to make a deep copy of a graph? Nodes in a graph can have references to any other node in a graph, will need to make copies of nodes and make sure nodes in copy refer to other copied nodes rather than the original nodes 9