Name: USC NetID (e.g., ttrojan): CS 455 Midterm Exam 2 Fall 2016 [Bono] November 8, 2016 There are 7 problems on the exam, with 50 points total available. There are 8 pages to the exam (4 pages double-sided), including this one; make sure you have all of them. If you need additional space to write any answers, pages 7 and 8 of the exam are left blank for that purpose. If you use these pages for answers you just need to direct us to look there. Do not detach any pages from this exam. Note: if you give multiple answers for a problem, we will only grade the first one. Avoid this issue by labeling and circling your final answers and crossing out any other answers you changed your mind about (though it s fine if you show your work). Put your name and USC username (a.k.a., NetID) at the top of the exam. Also put your NetID at the top right of the front side of each page of the exam. Please read over the whole test before beginning. Good luck! Set<ElmtType> Interface The classes that implement this interface are: TreeSet and HashSet. Selected methods: boolean contains(elmttype elmt) int size() boolean add(elmttype elmt) boolean remove(elmttype elmt) boolean isempty() Iterator<ElmtType> iterator() Returns true iff elmt is in the set Returns number of elements in the set Ensures that elmt is in the set. Returns true iff the set changed as a result of this call Removes elmt from the set. Returns true iff the set changed as a result of this call Returns true iff the set contains no elements. Returns an iterator over the elements in the set. String Class (selected methods) int length() boolean isempty() Returns the number of characters in the string. Returns true iff this is an empty string. char charat(int index) Returns the character at the specified index. PRE: 0 <= index < length() String substring(int beginindex, int endindex) Returns a new string that has the characters from positions beginindex through endindex-1 from this string. PRE: 0 <= beginindex <= length() and 0 <= endindex <= length() and beginindex <= endindex String substring(int beginindex) Returns a new string that has the characters from positions beginindex through the end of this string. PRE: 0 <= beginindex < =length() 1
Problem 1 [7 points] Give the big-o worst case time to solve each of the following problems (put your answers in the space provided to the left): 1. search for a value in a sorted array of size n 2. reverse the values in an array of size n 3. use insertion sort to sort n values in an array 4. compute the minimum and maximum values in an array of size n 5. do list.get(i) where list is a Java LinkedList object of size n 6. do list.get(i) where list is a Java ArrayList object of size n 7. determine whether a linked list is already sorted Problem 2 [4 points] Suppose you are implementing your own Stack class. For each of the following, answer one of: front, end, or doesn't matter. Part A. For a LinkedList representation of a Stack (i.e., using the Java LinkedList class), it would be most efficient to keep the top of the stack at which end of the list? Part B. For an ArrayList representation of a Stack, it would me most efficient to keep the top of the stack at which end of the array list? 2
Problem 3 [2 points] Part A. For each loop iteration of binary search in an array, we eliminate roughly how many elements from further consideration? Circle the one that matches most closely. In the following, k is the number of values that are still being considered at the start of that iteration. a. 1 b. log 2 k c. k/2 d. k-1 Part B. Answer the same question for linear search in an array. Circle the best choice: a b c d Problem 4 [4 points] In addition to a default (i.e., no-parameter) constructor, the TreeSet class has a second constructor that takes a Comparator as a parameter. Relevant documentation provided below: Comparator<Type> interface An object that can compare two objects of type Type. Has one method defined by the interface: int compare(type object1, Type object2) Must return a negative number if object1 should come before object2, 0 if object1 and object2 are equal, or a positive number if object1 should come after object2. Selected TreeSet<ElmtType> constructors: TreeSet<ElmtType>() Creates an empty TreeSet, sorted according to the natural ordering of its elements. TreeSet<ElmtType>(Comparator<ElmtType> comp) Creates an empty TreeSet, sorted according to the specified comparator. Why would the second constructor be useful? Explain by describing a scenario where we would need to use the second a constructor for a TreeSet and why. (Please limit your response to one or two sentences. Do not write code.) 3
Problem 5 [6 points] Consider the following program that uses exceptions. Note: MyException and FileNotFoundException are both subclasses of IOException: public class MyProg { public static void main(string[] args) { try { ArrayList<String> lines = readfile(); int maxsofar = 0; for (int i = 0; i < lines.size(); i++) { if (lines.get(i).length() > maxsofar) { maxsofar = lines.get(i).length(); System.out.println("Max line is " + maxsofar); catch (MyException exc) { System.out.println("Error #1"); catch (IOException exc) { System.out.println("Error #2"); public static ArrayList<String> readfile() throws IOException { ArrayList<String> lines = new ArrayList<String>(); try { Scanner infile = new Scanner(new File("inputData")); if (!infile.hasnext()) { throw new MyException(); while (infile.hasnextline()) { lines.add(infile.nextline()); catch (FileNotFoundException exc) { System.out.println("Error #3"); return lines; What is the output of the program for each of the following scenarios (show your answer to the right of each): 1. The file inputdata is empty. 2. The file inputdata has the contents: the elephant went to the zoo today 3. The file inputdata does not exist. 4
Problem 6 [7 points] Consider the following Student class that overrides equals and hashcode from Object: (Note: this is a different version of this class than we saw in lecture recently.) public class Student { private String name; private int score; public Student(String name, int score) { this.name = name; this.score = score; public boolean equals(object otherobject) { // code to check that the two objects are the same type not shown... //... Student other = (Student) otherobject; return name.equals(other.name); public int hashcode() { return name.hashcode() + score; //other methods not shown... The above code does not obey the contract for hashcode and equals, which is if a.equals(b) then a.hashcode() == b.hashcode() Give a sample code snippet using a HashSet that exposes the problem with the Student class provided, along with an explanation of what happens with the code related to this issue. The cover page of the exam has some Set documentation. Your code should use the variable defined for you below: Set<Student> section = new HashSet<Student>(); // creates an empty set Put your explanation here: 5
Problem 7 [20 points] Write a recursive boolean method to tell use whether a String is a set of matched parentheses. For the purposes of this problem we will narrowly define what is considered a set of matched parentheses, as illustrated by the examples below. A solution that doesn t use recursion or has a loop will receive little to no credit. Notes: solutions which include calls to substring can receive full credit, and (as usual) you are allowed to define a helper method to do the actual recursion. The cover page of the exam has some String documentation. Examples: str matched(str) str matched(str) true () true (() false ()) false (()) true (a) false ((((())))) true ( false )( false ()(()) false a false a(b(abc)de)fg false // returns true iff the String is a set of matched parentheses. (uses recursion) public static boolean matched(string str) 6
Extra space for answers or scratch work. (DO NOT detach this page.) If you put any of your answers here, please write a note on the question page directing us to look here. Also label any such answers here with the question number and part, and circle the answer. 7
Extra space for answers or scratch work (cont.) (DO NOT detach this page.) If you put any of your answers here, please write a note on the question page directing us to look here. Also label any such answers here with the question number and part, and circle the answer. 8