Model Solutions. COMP 103: Test April, 2013

Similar documents
Model Solutions. COMP 103: Test May, 2013

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

Model Solutions. COMP 103: Mid-term Test. 19th of August, 2016

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

EXAMINATIONS 2017 TRIMESTER 2

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

EXAMINATIONS 2013 COMP 103 INTRODUCTION TO DATA STRUCTURES AND ALGORITHMS

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

EXAMINATIONS 2015 COMP103 INTRODUCTION TO DATA STRUCTURES AND ALGORITHMS

COMP 103 : Test. 2018, Sept 12//(Corrected)

EXAMINATIONS 2016 TRIMESTER 2

COMP103 Test. 5 Sept, 2007

COMP 103 : Test. 2019, Jan 9 ** WITH SOLUTIONS **

COMP 103 : Test. 2018, Sept 12//(Corrected) ** WITH SOLUTIONS

EXAMINATIONS 2012 MID YEAR. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS

SOLUTIONS. COMP103 Introduction to Data Structures and Algorithms

EXAMINATIONS 2010 MID YEAR. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS

EXAMINATIONS 2010 END YEAR. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS

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

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

****** NOTE!! THIS CONTAINS SOLUTIONS ***** TRIMESTER 2

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 PRACTICE EXAM

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

CONTAINS SOLUTIONS!!!

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

COMP 103 Introduction to Data Structures and Algorithms

EXAMINATIONS 2011 END YEAR. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS

EXAMINATIONS 2006 SUMMER TRIMESTER. COMP103 Introduction to Data Structures and Algorithms

Class 32: The Java Collections Framework

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

CS61BL: Data Structures & Programming Methodology Summer 2014

EXAMINATIONS 2012 END-OF-YEAR COMP 103 INTRODUCTION TO DATA STRUCTURES AND ALGORITHMS

CSE 143 Au03 Final Exam Page 1 of 15

Topic 10: The Java Collections Framework (and Iterators)

CSC 321: Data Structures. Fall 2016

CSC 321: Data Structures. Fall 2017

CSC 1214: Object-Oriented Programming

CS61BL: Data Structures & Programming Methodology Summer 2014

11-1. Collections. CSE 143 Java. Java 2 Collection Interfaces. Goals for Next Several Lectures

DM550 Introduction to Programming part 2. Jan Baumbach.

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

CONTAİNERS COLLECTİONS

Te Whare Wananga o te Upoko o te Ika a Maui EXAMINATIONS 2003 END-YEAR COMP 103. Data Structures and Algorithms

NAME: c. (true or false) The median is always stored at the root of a binary search tree.

COMP 103. Data Structures and Algorithms

Java Collections Framework. 24 April 2013 OSU CSE 1

PIC 20A Collections and Data Structures

Java Collections. Readings and References. Collections Framework. Java 2 Collections. CSE 403, Spring 2004 Software Engineering

Topic #9: Collections. Readings and References. Collections. Collection Interface. Java Collections CSE142 A-1

COMP 102: Test August, 2017

CMSC 206: Data Structures Final Exam Reference May 2018

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

Java Collections. Readings and References. Collections Framework. Java 2 Collections. References. CSE 403, Winter 2003 Software Engineering

Taking Stock. IE170: Algorithms in Systems Engineering: Lecture 7. (A subset of) the Collections Interface. The Java Collections Interfaces

Sets and Maps. Part of the Collections Framework

Computer Science 62. Bruce/Mawhorter Fall 16. Midterm Examination. October 5, Question Points Score TOTAL 52 SOLUTIONS. Your name (Please print)

Model Solutions. COMP 102: Test 1. 6 April, 2016

University of Maryland College Park Dept of Computer Science

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

182 review 1. Course Goals

Question 0. (1 point) Write the correct ID of the section you normally attend on the cover page of this exam if you have not already done so.

FINAL EXAMINATION. COMP-250: Introduction to Computer Science - Fall 2011

Summer Final Exam Review Session August 5, 2009

Fall 2017 Mentoring 7: October 9, Abstract Data Types

An Interface with Generics

Java Magistère BFA

CSE143 Midterm Summer Name of Student: Section (e.g., AA): Student Number:

Important Dates. Game State and Tree. Today s topics. Game Tree and Mini-Max. Games and Mini-Max 3/20/14

CS171 Midterm Exam. October 29, Name:

COMP 250. Lecture 29. interfaces. Nov. 18, 2016

Implementing a List in Java. CSE 143 Java. List Interface (review) Just an Illusion? Using an Array to Implement a List.

Csci 102: Sample Exam

Building Java Programs

COMP 102: Test August, 2017

The Collections API. Lecture Objectives. The Collections API. Mark Allen Weiss

Introduction to Computing II (ITI 1121) Final Examination

Topics for CSCI 151 Final Exam Wednesday, May 10

COMP 103. Mid Trimester Test 17 August 2006

infix expressions (review)

40) Class can be inherited and instantiated with the package 41) Can be accessible anywhere in the package and only up to sub classes outside the

Computer Science 62. Midterm Examination

Implementation. Learn how to implement the List interface Understand the efficiency trade-offs between the ArrayList and LinkedList implementations

Collections (Java) Collections Framework

COMP103 Summer: Midterm

Collections class Comparable and Comparator. Slides by Mark Hancock (adapted from notes by Craig Schock)

Lecture 15 Summary. Collections Framework. Collections class Comparable and Comparator. Iterable, Collections List, Set Map

Midterm Exam 2 CS 455, Spring 2011

Programming Languages and Techniques (CIS120)

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

Recap. List Types. List Functionality. ListIterator. Adapter Design Pattern. Department of Computer Science 1

27/04/2012. Objectives. Collection. Collections Framework. "Collection" Interface. Collection algorithm. Legacy collection

CS2110: Software Development Methods. Maps and Sets in Java

Implementing a List in Java. CSE 143 Java. Just an Illusion? List Interface (review) Using an Array to Implement a List.

Chapter 5 Java Collection. Wang Yang

Generics Collection Framework

Abstract data types (again) Announcements. Example ADT an integer bag (next) The Java Collections Framework

CSE 143 Final Part 1, August 18, 2011 Sample Solution

Java Collection Framework

Computer Science First Exams Pseudocode Standard Data Structures Examples of Pseudocode

Standard ADTs. Lecture 19 CS2110 Summer 2009

Transcription:

Family Name:............................. Other Names:............................. ID Number:............................... Signature.................................. Instructions Time allowed: 40 minutes There are 40 marks in total. Answer all the questions. Model Solutions COMP 103: Test 1 11 April, 2013 Write your answers in the boxes in this test paper and hand in all sheets. Ask for additional paper if you need it. If you think some question is unclear, ask for clarification. Brief Java documentation is supplied on the last page. This test will be converted to 15% of your final grade (but your mark will be boosted up to your exam mark if that is higher.) You may use paper translation dictionaries, and calculators without a full set of alphabet keys. You may write notes and working on this paper, but make sure it is clear where your answers are. Questions Marks 1. Collections [10] 2. Programming with Collections [14] 3. Using an iterator [7] 5. Costs, and Simple sorts [9] TOTAL:

Question 1. Collections [10 marks] For each of these programming tasks, state what kind of collection you would use, and justify why you chose that kind of collection. (a) [2 marks] A collection recording the coffee orders in a cafe. The coffees are made in the sequence they were requested, and the program needs to provide only the next coffee order to be made. Collection Type: Queue Justification: It s a queue of coffee orders, so duplicates are allowed (not a Set). But they are made in the order requested, and only the most pressing order needs to be displayed, hence a Queue is the right Collection to use. (b) [2 marks] A collection recording the people currently attending an event. New people may arrive at any time, or existing attendees may depart, but at any time the collection needs be able to provide a list of all the people currently at the event. Collection Type: Set Justification: Attendees form a Set because duplicates should not be allowed. However there is no requirement for ordering, just attendance. Hence a Set. (c) [2 marks] A collection recording the current inventory of a store. Upon request, the program needs to be able to provide the number of items of a certain type of stock that the store currently has. Collection Type: Map. Justification: The user will look up a type of item ( Socks ) and get a number (119), so what is required is a Map from Strings to Integers. (Question 1 continued on next page) COMP 103 (Terms Test 1) 2 continued...

(Question 1 continued) (d) [2 marks] A Set is a collection that has no ordering, and we have looked at an implementations of this that store the items in an array. It can still be a good idea to implement it by using a sorted array, rather than an unsorted one. Explain why. If the Set is stored in sorted form, we can use the binary search algorithm to search it. This is much (much) faster than the linear search required if the array is not sorted. (e) [2 marks] In the box below, fix the error(s) in the following declaration for a Set of strings: Set localset = new Set <String> ; corrected version: Set <String> localset = new HashSet <String> (); (or some other valid Set implementation).. COMP 103 (Terms Test 1) 3 continued...

Question 2. Programming with Collections [14 marks] This question is about a program called SongsOrganiser, that manages information about a playlist of Songs. Consider the following code for a Song class, which does nothing except store information: public class Song { private int year; private String artist, title ; // constructor public Song(String artist, String title, int yr) { this.year = yr; this. artist = artist ; this. title = title ; // some get methods to provide information. public String getartist () { return artist ; public String gettitle () { return title ; public Integer getyear() { return year; A real SongsOrganiser program would probably read in data from a large file. The demo version shown here just creates some Song objects explicitly, and stores them in a List of Songs: public class SongsOrganiser { // constructor public SongsOrganiser() { List <Song> songlist = new ArrayList <Song> (); songlist. add(new Song("Phoenix Foundation", "Hitchcock",2005)); songlist. add(new Song("Phoenix Foundation", "Buffalo",2010)); songlist. add(new Song("Dresden Dolls", "Shores of California",2007)); songlist. add(new Song("Tiny Ruins", "Priest with balloons",2011)); : songlist. add(new Song("Azelia Banks", "212",2011)); songlist. add(new Song("SJD", "Beautiful haze",2007)); // Set up a map from artist names to Songs Map <String, List<Song>> songmap; songmap = makemapofsongs(songlist); // to be written, question 2a. sorteachartist(songmap); // to be written, question 2b. // methods : COMP 103 (Terms Test 1) 4 continued...

The questions here ask you to write the methods mentioned in the last two lines above, which would go into the SongsOrganiser class. (a) [9 marks] Write the method makemapofsongs, which takes a List of Song objects, and returns a Map from artist names to Songs. You may assume that each song appears only once in the original List. HINT: write out the necessary steps as pseudocode first. public Map <String, List<Song>> makemapofsongs( List<Song> allsongs ) { // Make a new map. Map <String, List<Song>> mymap = new HashMap <String, List<Song>> (); // Build up a map of artists and lists first, in any order. for (Song b : allsongs) { String art = b. getartist (); if (mymap.keyset().contains(art)) { mymap.get(art).add(b); // add to an existing list else { List <Song> mylist = new ArrayList <Song> (); // a new list mylist.add(b); // add to the new list mymap.put(art,mylist); // list is the map s value for this key return mymap; COMP 103 (Terms Test 1) 5 continued...

(Question 2 continued on next page) COMP 103 (Terms Test 1) 6 continued...

(Question 2 continued) (b) [5 marks] Write the method sorteachartist, which takes the current Map, and sorts the List of Songs associated with each artist into ascending order by year. A comparator is provided, and you should consider using the Collections.sort() method described in documentation at the end of this test. public void sorteachartist(map <String, List<Song>> mymap) { // EITHER THIS... for (String art : mymap.keyset()) { List <Song> mylist = mymap.get(art); Collections. sort( mylist, new SongComparator()); mymap.put(art,mylist); // put it back... // NB. final line not essential, as Collections. sort () is in place // OR THIS, which works because Collections. sort () is in place... for ( List <Song> sl : mymap.values()) Collections. sort( sl, new SongComparator()); / Comparator that will order Songs based on their year. / private class SongComparator implements Comparator <Song> { public int compare (Song song1, Song song2) { return (song1.getyear() song2.getyear()); COMP 103 (Terms Test 1) 7 continued...

SPARE PAGE FOR EXTRA ANSWERS Cross out rough working that you do not want marked. Specify the question number for work that you do want marked. COMP 103 (Terms Test 1) 8 continued...

Question 3. Using an iterator [7 marks] Consider the following code for a random number generator: public class RandNumIterator implements Iterator <Integer> { private int num = 1; public boolean hasnext() { return true; public Integer next() { num = (num 92863) % 104729 + 1; return num; public void remove(){ throw new UnsupportedOperationException(); (a) [2 marks] Why is the remove method included here, when all it does is throw an exception? It is required for the interface Iterator (b) [5 marks] Complete the following method, that first creates a RandNumIterator (an instance of the class given above) and then uses it to print out N random numbers. private void printnnumbers(int N) { Iterator <Integer> lottery = new RandNumIterator(); for ( int i=1; i<n; i++) System.out.println( lottery. next ()); COMP 103 (Terms Test 1) 9 continued...

Question 4. Costs and Simple sorts [9 marks] (a) [5 marks] Give the cost, in big-o notation, of the following ArraySet operations (assuming the array is not sorted), for a Set of size n. Include a justification in each case. The first one is done for you as an example. Cost of contains: O(n) REASON: The array is unsorted, so you have no option but to search it element-by-element. With n items, you will find the item after looking at n/2 on average, which we say is of order n. Cost of add: O(n) REASON: because you have to first check it s not in the Set already Cost of remove: O(n) REASON: because you have to find it first Now do the same for a SortedArraySet implementation, in which the array containing the data items is maintained in a sorted order. Cost of contains: O(log n) REASON: binary search can find it in a mere log n comparisons! Cost of add: O(n) REASON: although you can check it s not there, adding it is harder: can t go at end Cost of remove: O(n) REASON: you can find it quickly, but removal requires moving everything down to fill the gap (b) [4 marks] In words, explain why the InsertionSort algorithm has cost O(n 2 ) on lists that are randomly ordered to start with, but has cost O(n) on lists that are nearly sorted to start with. Cost on randomly ordered Lists is O(n 2 ), because... InsertionSort repeatedly takes next item and finds where to put it in the List up to that point. The outer loop goes around n times, and each time runs an inner loop going backwards to figure out where the new item goes: this is linear in n, hence O(n 2 ). Cost on nearly-ordered Lists becomes O(n), because... The inner loop now only has one comparison to do (not n/2 or so), hence O(n). COMP 103 (Terms Test 1) 10

******************************** COMP 103 (Terms Test 1) 11 continued...

appendix Some brief and truncated documention that may be helpful: interface Collection<E> public boolean isempty() public int size () public boolean add(e item) public boolean contains(object item) public boolean remove(object element) public Iterator <E> iterator() interface List <E> extends Collection<E> // Implementations: ArrayList, LinkedList public E get( int index) public E set( int index, E element) public void add(int index, E element) public E remove(int index) // plus methods inherited from Collection interface Set extends Collection<E> // Implementations: ArraySet, HashSet, TreeSet // methods inherited from Collection interface Queue<E> extends Collection<E> // Implementations: ArrayQueue, LinkedList public E peek () // returns null if queue is empty public E poll () // returns null if queue is empty public boolean offer (E element) // returns false if fails to add class Stack<E> implements Collection<E> public E peek () // returns null if stack is empty public E pop () // returns null if stack is empty public E push (E element) // returns element being pushed interface Map<K, V> // Implementations: HashMap, TreeMap, ArrayMap public V get(k key) // returns null if no such key public V put(k key, V value) // returns old value, or null public V remove(k key) // returns old value, or null public boolean containskey(k key) public Set<K> keyset() public class Collections public void sort( List <E>) public void sort( List <E>, Comparator<E>) public void shuffle( List <E>, Comparator<E>)