CS 61B Spring 2017 Guerrilla Section 3 Solutions

Similar documents
CS 61B Spring 2017 Guerrilla Section 3 Worksheet. 25 February 2017

CS61B Spring 2016 Guerrilla Section 2 Worksheet

Java classes cannot extend multiple superclasses (unlike Python) but classes can implement multiple interfaces.

CS 61B Guerrilla Section 1 Worksheet

CS 61B Midterm 2 Guerrilla Section Spring 2018 March 17, 2018

EXAMINATIONS 2011 Trimester 2, MID-TERM TEST. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS

Basic Data Structures

EXAMINATIONS 2015 COMP103 INTRODUCTION TO DATA STRUCTURES AND ALGORITHMS

CS 61B Guerrilla Section 1 Solution

Introduction to Computing II (ITI 1121) Final Examination

Basic Data Structures 1 / 24

CS61BL Summer 2013 Midterm 2

CS 61B Spring 2017 Guerrilla Section 4 Worksheet. 11 March 2017

CMSC 132: Object-Oriented Programming II. Stack and Queue

csci 210: Data Structures Stacks and Queues

CMP Points Total Midterm Spring Version (16 Points) Multiple Choice:

INFO1x05 Tutorial 6. Exercise 1: Heaps and Priority Queues

CS/ENGRD 2110 SPRING Lecture 7: Interfaces and Abstract Classes

Examination Questions Midterm 1

CE204 Data Structures and Algorithms Part 2

Interfaces & Generics

DNHI Homework 3 Solutions List, Stacs and Queues

EXAMINATIONS 2016 TRIMESTER 2

EXAMINATIONS 2017 TRIMESTER 2

Project 2 (Deques and Randomized Queues)

182 review 1. Course Goals

Family Name:... Other Names:... ID Number:... Signature... Model Solutions. COMP 103: Test 1. 9th August, 2013

CSE 143 Lecture 26. Advanced collection classes. (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, ,

CS61BL: Data Structures & Programming Methodology Summer Midterm 1 Solutions. public static boolean probablyequals( Object obj1, Object obj2 ) {

CT 229 Object-Oriented Programming Continued

Data Abstraction and Specification of ADTs

(f) Given what we know about linked lists and arrays, when would we choose to use one data structure over the other?

EXAMINATIONS 2012 Trimester 1, MID-TERM TEST. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS

Spring 2018 Discussion 6: February 19, 2018

Practice Questions for Final Exam: Advanced Java Concepts + Additional Questions from Earlier Parts of the Course

Points off Total off Net Score. CS 314 Final Exam Spring 2016

CMPSCI 187: Programming With Data Structures. Lecture 12: Implementing Stacks With Linked Lists 5 October 2011

CSE 143 SAMPLE MIDTERM

Insertions and removals follow the Fist-In First-Out rule: Insertions: at the rear of the queue Removals: at the front of the queue

SOLUTIONS. COMP103 Introduction to Data Structures and Algorithms

Collections, Maps and Generics

17. Java Collections. Organizing Data. Generic List in Java: java.util.list. Type Parameters ( Parameteric Polymorphism ) Data Structures that we know

COMP103 Test. 5 Sept, 2007

Model Solutions. COMP 103: Test April, 2013

Standard ADTs. Lecture 19 CS2110 Summer 2009

CMP Points Total Midterm Spring Version (16 Points) Multiple Choice:

Prelim 1. CS 2110, October 1, 2015, 5:30 PM Total Question Name True Short Testing Strings Recursion

Implementing Dynamic Data Structures

Building Java Programs

Exceptions and Design

Name CPTR246 Spring '17 (100 total points) Exam 3

Queues. Stacks and Queues

Model Solutions. COMP 103: Mid-term Test. 21st of August, 2014

STANDARD ADTS Lecture 17 CS2110 Spring 2013

Stacks have many uses Arithmetic Language parsing Keeping track of recursion (more in this in a week or so)

Stacks and Queues. Gregory D. Weber. CSCI C243 Data Structures

Midterm Exam 2 CS 455, Spring 2011

ITI Introduction to Computing II

CS171 Midterm Exam. October 29, Name:

Advanced Java Concepts Unit 3: Stacks and Queues

Summer Final Exam Review Session August 5, 2009

CSE 332: Data Structures. Spring 2016 Richard Anderson Lecture 1

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

cs Java: lecture #6

double d0, d1, d2, d3; double * dp = new double[4]; double da[4];

EXAMINATIONS 2005 END-YEAR. COMP 103 Introduction to Data Structures and Algorithms

Abstract Data Types (ADTs) Queues & Priority Queues. Sets. Dictionaries. Stacks 6/15/2011

CMSC 132, Object-Oriented Programming II Summer Lecture 9:

Day 6. COMP1006/1406 Summer M. Jason Hinek Carleton University

Abstract Data Types Spring 2018 Exam Prep 5: February 12, 2018

COMP 103 Introduction to Data Structures and Algorithms

CS 61B Discussion 5: Inheritance II Fall 2014

Abstract vs concrete data structures HEAPS AND PRIORITY QUEUES. Abstract vs concrete data structures. Concrete Data Types. Concrete data structures

Topic 10: The Java Collections Framework (and Iterators)

WITH SOLUTIONS!!! WARNING: THIS COPY CONTAINS SOLUTIONS!!! COMP103 Introduction to Data Structures and Algorithms

Announcements HEAPS & PRIORITY QUEUES. Abstract vs concrete data structures. Concrete data structures. Abstract data structures

CSCI-140 Midterm Review October 10, 2015 Presented by the RIT Computer Science Community

COMP250: Stacks. Jérôme Waldispühl School of Computer Science McGill University. Based on slides from (Goodrich & Tamassia, 2004)

Lecture 6. COMP1006/1406 (the OOP course) Summer M. Jason Hinek Carleton University

CSCI-142 Exam 2 Review November 2, 2018 Presented by the RIT Computer Science Community

type conversion polymorphism (intro only) Class class

Stacks (5.1) Abstract Data Types (ADTs) CSE 2011 Winter 2011

Inheritance. Transitivity

CSC 1351: Final. The code compiles, but when it runs it throws a ArrayIndexOutOfBoundsException

Building Java Programs

CSE 373 Data Structures and Algorithms. Lecture 2: Queues

U N I V E R S I T Y O F W E L L I N G T O N EXAMINATIONS 2018 TRIMESTER 2 COMP 103 INTRODUCTION TO DATA STRUCTURES AND ALGORITHMS

Queues. CITS2200 Data Structures and Algorithms. Topic 5

Introduction to Computing II (ITI 1121) Final Examination

CS 455 Midterm Exam 2 Fall 2016 [Bono] November 8, 2016

Introduction to Computer Science II (ITI 1121) Final Examination

Chapter 13 Object Oriented Programming. Copyright 2006 The McGraw-Hill Companies, Inc.

CS 61B Spring 2017 Guerrilla Section 2 Worksheet. 12 February 2017

COMP 250. Lecture 32. polymorphism. Nov. 25, 2016

CS61B Spring 2016 Guerrilla Section 3 Worksheet. 12 March 2016

Please note that if you write the mid term in pencil, you will not be allowed to submit a remark request.

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are "built" on top of that.

Symbol Tables 1 / 15

I have neither given nor received any assistance in the taking of this exam.

COMP 250. Lecture 30. inheritance. overriding vs overloading. Nov. 17, 2017

Transcription:

Spring 2017 25 February 2017 Directions: In groups of 4-5, work on the following exercises. Do not proceed to the next exercise until everyone in your group has the answer and understands why the answer is what it is. Of course, a topic appearing on this worksheet does not imply that the topic will appear on the midterm, nor does a topic not appearing on this worksheet imply that the topic will not appear on the midterm. 1 Probably Equal? (a) Warm-up! What is the difference between == and.equals? == compares object references (i.e. do they point to the same address in memory)..equals calls the equals method. Would it make sense for the scenarios below to occur? Explain why or why not. i A.equals(B) but A!= B Yes. You can have a copy of an object which will be a different object reference. ii A == B but!a.equals(b) No. If A == B, A and B are the exact same object reference and should be considered equal by the.equals method. (b) Write a probablyequals method that takes in two objects and returns true if one or more of the following are true: The two objects are equal (.equals) to each other. The two objects are equal (==) to each other. The two objects have the same.tostring() representation. Otherwise, probablyequals returns false. Your method should never crash given any input. You may assume that for any object instances x and y, x.equals(y) will return the same value as y.equals(x). You may also assume that every object has a unique non-random tostring representation. Note:.equals(Object o) and.tostring() are methods that every object subclass inherits from the Object class. 1

1 // Solution 2 public static boolean probablyequals ( Object obj1, Object obj2 ) { 3 if ( obj1 == obj2 ) { // Put this first, consider the case where both are null 4 return true ; 5 6 if ( obj1 == null obj2 == null ) { // Must be before method calls! 7 return false ; 8 9 if ( obj1. equals ( obj2 )) { 10 return true ; 11 12 if ( obj1. tostring (). equals ( obj2. tostring ())) { // Strings are objects, use. equals 13 return true ; 14 15 return false ; // default 16 Spring 2017 2

2 Expandable Set Using inheritance, define a class TrackedQueue that behaves like Queue except for an extra method, maxsizesofar() which returns an integer corresponding to the maximum number of elements in this queue since it was constructed. Assume that the Queue class is a non-abstract class with the following methods defined: void enqueue(object obj) int size() Object dequeue() 1 // Solution 2 public class TrackedQueue extends Queue { 3 private int maxsize ; 4 public TrackedQueue () { 5 super (); 6 maxsize = 0; 7 8 9 public int maxsizesofar () { 10 return maxsize ; 11 12 13 public int enqueue ( Object obj ) { 14 super. enqueue ( obj ); 15 if ( super. size () > maxsize ) { 16 maxsize = super. size (); 17 18 19 Spring 2017 3

3 Xzibit s ADTs Consider the following abstract data type definitions: 1 List <E > { 2 void insert ( E item, int position ); 3 E remove ( int position ); 4 E get (int position ); 5 int size (); 6 7 8 Set <E > { 9 void add (E item ); 10 void remove (E item ); 11 boolean contains ( E item ); 12 Iterator <E> list (); 13 14 15 Stack <E > { 16 void push (E item ); 17 E pop (); 18 boolean isempty (); 19 20 21 Queue <E > { 22 void enqueue ( E item ); 23 E dequeue (); 24 boolean isempty (); 25 26 27 Map <K, V> { 28 put (K key, V value ); 29 remove (K key ); 30 V get (K key ); 31 Iterator <K> keys (); 32 For the following questions, you may assume the above data types have been implemented as classes. (a) Write an extension of the Set class, called IntegerSet, with the following methods: void add(integer item): adds an integer to the set boolean contains(integer item):checks item for membership in the set Iterator<Integer> list():returns an iterator over the elements of the IntegerSet Integer max():returns the maximum value in the IntegerSet, or null if the set is empty 1 public class IntegerSet extends Set < Integer > { 2 public Integer max () { 3 Iterator < Integer > iter = list (); 4 Integer maxsofar = null ; 5 while ( iter. hasnext ()) { 6 Integer curr = iter. next (); 7 if ( maxsofar == null maxsofar < curr ) { 8 maxsofar = curr ; 9 10 11 return maxsofar ; 12 13 Spring 2017 4

(b) Consider the following PriorityQueue interface: public interface PriorityQueue<E> { public void enqueue(e item, int priority); public E dequeue(); public E peek(); Describe how you would implement this abstract data type using any combination of the above ADT definitions, including IntegerSet. One could use a map of priorities to lists of items with that priority. It is possible to iterate over the keys of the Map to find the maximum priority, or throw the keys into an IntegerSet and get the max that way. When an item is dequeued, it is removed from the list that it?s priority maps to; the key-value pair is destroyed if the dequeued item was the last item with that priority. Enqueueing checks to see if a list of items with the enqueued item?s priority is already present, and adds to that list if so. Otherwise, a new key-value pair is created. Spring 2017 5

4 Delegation vs. Extension Consider the following class. interface MyStack<T> { void push(t item); T pop(); int size(); (a) Implement ExtensionStack which implements MyStack using extension, without using the new keyword. (Hint: ExtensionStack can extend LinkedList). public class ExtensionStack<T> extends LinkedList<T> implements MyStack<T> { public void push(t item) { addfirst(item); public T pop() { if (isempty()) { throw new NoSuchElementException("Empty Stack!"); return removefirst(); public boolean isempty() { return super.isempty(); (b) Implement DelegationStack which implements MyStack using delegation. public class DelegationStack<T> implements MyStack<T> { LinkedList<T> data = new LinkedList<>(); public void push(t item) { data.addfirst(item); public T pop() { if (data.isempty()) { throw new NoSuchElementException("Empty Stack!"); return data.removefirst(); public boolean isempty() { return data.isempty(); public int size() { return data.size(); Spring 2017 6

5 FunkySets & Promotion Cross out the lines that would cause compilation errors for each of the classes. Write out the values that will be printed where indicated in the code?s comments. 1 import java. util. HashSet ; 2 public class FunkySet { 3 public static void main ( String [] args ){ 4 HashSet <int > set = new HashSet <int >(); // does not compile 5 HashSet < Integer > set = new HashSet <int >(); // does not compile 6 HashSet <int > set = new HashSet < Integer >(); // does not compile 7 HashSet < Integer > set = new HashSet < Integer >(); 8 int x = 3; 9 set. add (x); 10 set. add (4) ; 11 Integer y = 5; 12 set. add (y); 13 System. out. println ( set. tostring ()); // {3, 4, 5 14 if ( set. contains (x)){ 15 set. remove (x); 16 17 if ( set. contains (4) ){ 18 int z = 4; 19 set. remove (z); 20 21 if ( set. contains (y)){ 22 set. remove (y); 23 24 System. out. println ( set. tostring ()); // { 25 26 27 public class FunkySetTwo { 28 public static void main ( String [] args ){ 29 int [][] x = new int [2][3]; 30 Integer [][] y = new Integer [2][3]; 31 Integer [][] z = new int [2][3]; // doesn t compile 32 Integer [] arrayone = {1,2,3; 33 int [] arraytwo = {4,5,6; 34 35 x[0] = arrayone ; // doesn t compile 36 x[1] = arraytwo ; // compiles 37 38 y[0] = arrayone ; // compiles 39 y[1] = arraytwo ; // doesn t compile 40 41 z[0] = arrayone ; // doesn t compile 42 z[1] = arraytwo ; // doesn t compile 43 44 Spring 2017 7

1 public class Promotion { 2 public static void doubleprinter ( double num){ 3 System. out. println ( num ); 4 5 public static void longprinter ( long num){ 6 System. out. println ( num ); 7 8 public static void intprinter ( int num){ 9 System. out. println ( num ); 10 11 public static void intprintertwo ( Integer num){ 12 System. out. println ( num ); 13 14 public static void shortprinter ( short num){ 15 System. out. println ( num ); 16 17 public static void main ( String [] args ){ 18 int x = 45; 19 longprinter (x); // 45 20 doubleprinter (x); // 45.0 21 intprinter (( int )x); // 45 22 intprintertwo (x); // 45 23 shortprinter ( x); // doesn t work 24 shortprinter (( short ) x); // 45 25 26 6 Iterators Print ALL bark combinations of dogs from two dog lists in form of Woof DOG1! Woof DOG2!. The dogs in dogs1 should bark first. For 3 dogs in dogs1 and 5 dogs in dogs2, there must be 15 bark combinations printed. 1 public class Dog { 2 String name =...; 3 public void bark () { 4 System. out. print (" Woof " + name + "!"); 5 6 7 8 public static void barkcombinations ( Iterable <Dog > dogs1, Iterable <Dog > dogs2 ) { 9 for ( Dog dog1 : dogs1 ){ 10 for ( Dog dog2 : dogs2 ){ 11 dog1. bark (); 12 System. out. print (" "); 13 dog2. bark (); 14 System. out. println (); 15 16 17 Spring 2017 8

7 Iterator or Iterable? Implement the Filter class such that its main method correctly prints out the even numbers in the given collection. (Should print out 0 20 14 50 66 all on newlines) 1 public interface FilterCondition <T > { 2 /** Evaluates if the given item passes a certain condition ( ie, is even, a prime number, is icky, etc.) */ 3 public boolean eval ( T item ); 4 5 public class EvenCondition implements FilterCondition < Integer > { 6 public boolean eval ( Integer i) { 7 return i % 2 == 0; 8 9 10 import java. util. Arrays ; 11 import java. util. Iterator ; 12 import java. util. List ; 13 public class Filter implements Iterable < Integer > { 14 Iterable < Integer > iterable ; 15 FilterCondition < Integer > cond ; 16 17 public Filter ( Iterable < Integer > thingamajig, FilterCondition < Integer > cond ) { 18 iterable = thingamajig ; 19 this. cond = cond ; 20 21 22 public Iterator < Integer > iterator () { 23 return new FilterIterator (); 24 25 26 private class FilterIterator implements Iterator < Integer > { 27 Iterator < Integer > integeriterator ; 28 Integer toreturn ; 29 30 private FilterIterator () { 31 integeriterator = iterable. iterator (); 32 while ( integeriterator. hasnext ()) { 33 int x = integeriterator. next (); 34 if ( cond. eval (x)) { 35 toreturn = x; 36 break ; 37 38 39 40 41 public Integer next () { 42 Integer processed = toreturn ; 43 toreturn = null ; 44 while ( integeriterator. hasnext ()) { 45 int x = integeriterator. next (); 46 if ( cond. eval (x)) { 47 toreturn = x; 48 break ; 49 50 51 return processed ; 52 53 Spring 2017 9

54 public boolean hasnext () { 55 return toreturn!= null ; 56 57 58 59 public static void main ( String [] args ) { 60 List < Integer > arr = Arrays. aslist (new Integer []{0, 11, 20, 13, 14, 50, 66) ; 61 for ( int i : new Filter ( arr, new EvenCondition ())) { 62 System. out. println (i); 63 64 65 Spring 2017 10

8 Except Me for Who I Am Consider the following: 1 public class IntList { 2 private int head ; 3 private IntList tail ; 4 5 /* Returns the index of an element in the list */ 6 public int getindex ( int item ) { 7 int index = 0; 8 IntList temp = this ; 9 while ( temp. head!= item ) { 10 temp = temp. tail ; 11 index ++; 12 13 return index ; 14 15 16 public int getindexthrowexception ( int item ) throws IllegalArgumentException { 17 // YOUR CODE HERE 18 19 20 public int getindexdefaultnegative ( int item ) { 21 // YOUR CODE HERE 22 23 (a) What happens when you call getindex(int item) on an element that is not in the list? You will run into a NullPointerException. (b) Write getindexthrowexception, which attempts to get the index of an item, but throws an IllegalArgumentException with a useful message if no such item exists in the list. Do not use if statements, while loops, for loops, or recursion. (Hint: you can use get(int item)) (c) Write getindexdefaultnegative, which attempts to get the index of an item, but returns -1 if no such item exists in the list. Again, do not use if statements, while loops, for loops, or recursion. 1 public int getindexthrowexception ( int item ) throws IllegalArgumentException { 2 try { 3 int index ; 4 index = getindex ( item ); 5 return index ; 6 catch ( NullPointerException e) { 7 throw new IllegalArgumentException (" Tried to access a null object "); 8 9 10 11 public int getindexdefaultnegative ( int item ) { 12 try { 13 int index ; 14 index = getindex ( item ); 15 return index ; 16 catch ( NullPointerException e) { 17 return -1; 18 19 Spring 2017 11

Spring 2017 12

9 Generic Brand Generics For each of the modifications of maxkey from lecture (found on the next page), identify which lines fail to compile in the main method of MapHelperUser: 1 public class MapHelper { 2 /* maxkey belongs here */ 3 1 class Dog { 2 3 4 class Cat implements OurComparable { 5 public int compareto ( Object o) { 6 /* CODE NOT SHOWN */ 7 8 9 10 class Parrot implements Comparable < Parrot > { 11 public int compareto ( Parrot o) { 12 /* CODE NOT SHOWN */ 13 14 15 16 class Penguin <T > implements Comparable < Penguin <T >> { 17 public int compareto ( Penguin <T > o) { 18 /* CODE NOT SHOWN */ 19 20 21 22 class Sloth implements Comparable <T > { 23 public int compareto ( T o) { 24 /* CODE NOT SHOWN */ 25 26 1 class MapHelperUser { 2 public static void main ( String [] args ) { 3 Map <Dog, Integer > dogmap = new ArrayMap < >(); 4 Map < Integer, Dog > mapdog = new TreeMap < >(); 5 Map <Cat, String > catmap = new ArrayMap < >(); 6 Map < Parrot, Boolean > parrotmap = new ArrayMap < >(); 7 Map < Penguin < Float >, Long > penguinmap = new HashMap < >(); 8 Map < Sloth, Double > slothmap = new ArrayMap < >(); 9 10 // Assume maps are filled 11 12 Dog topdog = MapHelper. maxkey ( dogmap ); 13 Integer numberone = MapHelper. maxkey ( mapdog ); 14 Cat coolestcat = MapHelper. maxkey ( catmap ); 15 Parrot partyparrot = MapHelper. maxkey ( parrotmap ); 16 Penguin < Float > supremepenguin = MapHelper. maxkey ( penguinmap ); 17 Sloth slowsloth = MapHelper. maxkey ( slothmap ); 18 19 Spring 2017 13

The Sloth class does not compile. Should be Sloth<T>. Incorrect usage of generic. Greater Than Only numberone will run successfully because Integer will be unboxed to an int which can use the > comparison operator. 1 public static <K, V > K maxkey ( Map61B <K, V > map) { 2 List <K> keylist = map. keys (); 3 K largest = keylist. get (0) ; 4 for ( K k : keylist ) { 5 if (k > largest ) { 6 largest = k; 7 8 9 return largest ; 10 compareto (What s wrong with just using <K, V>?) topdog will fail to run because it has no compareto method. Using the naive <K, V> declaration does not enforce generic objects to have a compareto method. 1 public static <K, V > K maxkey ( Map61B <K, V > map) { 2 List <K> keylist = map. keys (); 3 K largest = keylist. get (0) ; 4 for ( K k : keylist ) { 5 if ( k. compareto ( largest ) > 0) { 6 largest = k; 7 8 9 return largest ; 10 OurComparable Only coolestcat will run successfully. The rest will error on compilation, as the rest of the animal classes do not implement OurComparable. 1 // Assume same body as above 2 public static <K extends OurComparable, V > K maxkey ( Map61B <K, V > map) Comparable<K> topdog and coolestcat will fail on compilation, as the Dog and Cat classes do not implement Comparable<K>. 1 // Assume same body as above 2 public static <K extends Comparable <K >, V > K maxkey ( Map61B <K, V > map) Spring 2017 14