QUEEN MARY, UNIVERSITY OF LONDON DCS128 ALGORITHMS AND DATA STRUCTURES Class Test Monday 27 th March

Similar documents
Use the supplementary boxes on the last sheet if you want to change any answer.

QUEEN MARY, UNIVERSITY OF LONDON DCS128 ALGORITHMS AND DATA STRUCTURES Class Test Monday 13 th February

QUEEN MARY, UNIVERSITY OF LONDON DCS128 ALGORITHMS AND DATA STRUCTURES Class Test Monday 13 th February

Birkbeck (University of London) Software and Programming 1 In-class Test Mar 2018

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Inheritance (Part 5) Odds and ends

Csci 102: Sample Exam

CS 251 Intermediate Programming Inheritance

1.00/1.001 Introduction to Computers and Engineering Problem Solving. Final Exam

Exam Duration: 2hrs and 30min Software Design

Birkbeck (University of London) Software and Programming 1 In-class Test Mar Answer ALL Questions

CS-140 Fall 2018 Test 2 Version A Nov. 12, Name:

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

Object-oriented Programming and Software Engineering CITS1001. Multiple-choice Mid-semester Test

Module Contact: Dr Geoff McKeown, CMP Copyright of the University of East Anglia Version 1

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented

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

Objects and Iterators

Topic 5 Polymorphism. " Inheritance is new code that reuses old code. Polymorphism is old code that reuses new code.

ITI Introduction to Computing II

Csci 102: Sample Exam

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

Solutions to Quiz 1 (March 14, 2016)

Rules and syntax for inheritance. The boring stuff

More about inheritance

MIT AITI Lecture 18 Collections - Part 1

Java Classes, Inheritance, and Interfaces

QUIZ 2 Introduction to Computer Science (COMP 250) Mon. March 2, 2009 Professor Michael Langer

CIS Fall Data Structures Midterm exam 10/16/2012

Collections Algorithms

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Java Magistère BFA

Aggregation and Composition. [notes Chapter 4]

CLASS DESIGN. Objectives MODULE 4

Polymorphism. return a.doublevalue() + b.doublevalue();

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

Inheritance, Polymorphism, and Interfaces

Java Fundamentals (II)

Supplementary Test 1

Introduction to Computing II (ITI 1121) Final Examination

public static boolean isoutside(int min, int max, int value)

TeenCoder : Java Programming (ISBN )

Comparing Objects 3/14/16

CS 113 MIDTERM EXAM 2 SPRING 2013

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

Module Contact: Dr Gavin Cawley, CMP Copyright of the University of East Anglia Version 1

3. Convert 2E from hexadecimal to decimal. 4. Convert from binary to hexadecimal

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

USAL1J: Java Collections. S. Rosmorduc

CS 455 Final Exam Fall 2012 [Bono] Dec. 17, 2012

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

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass?

Inheritance and Polymorphism

Outline. runtime of programs algorithm efficiency Big-O notation List interface Array lists

Making New instances of Classes

Prelim 1. CS2110, October 2, 2014, 5:30 PM Extra Total Question TrueFalse Multiple Object Oriented

Computer Science 2 Lecture 4 Inheritance: Trinidad Fruit Stand 02/15/2014 Revision : 1.7

Practice for Chapter 11

Prelim 1 Solutions. CS 2110, March 10, 2015, 5:30 PM Total Question True False. Loop Invariants Max Score Grader

Operators and Expressions

Introduction to Inheritance

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Sum this up for me. Let s write a method to calculate the sum from 1 to some n. Gauss also has a way of solving this. Which one is more efficient?

Prelim 1 SOLUTION. CS 2110, September 29, 2016, 7:30 PM Total Question Name Loop invariants. Recursion OO Short answer

CMSC132 Summer 2018 Midterm 1

CO Java SE 8: Fundamentals

CMSC 341. Nilanjan Banerjee

Super-Classes and sub-classes

Object Oriented Programming. Java-Lecture 11 Polymorphism

C12a: The Object Superclass and Selected Methods

CS-202 Introduction to Object Oriented Programming

Creating an Immutable Class. Based on slides by Prof. Burton Ma

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

Advanced Java Concepts Unit 2: Linked Lists.

INHERITANCE. Spring 2019

a) Answer all questions. b) Write your answers in the space provided. c) Show all calculations where applicable.

CS171:Introduction to Computer Science II

COE 212 Engineering Programming. Welcome to the Final Exam Thursday December 15, 2016

CMPS 12A Introduction to Programming Midterm 2 Review Problems

UMBC CMSC 331 Final Exam

CS 110 Practice Final Exam originally from Winter, Instructions: closed books, closed notes, open minds, 3 hour time limit.

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community

CSIS 10B Lab 2 Bags and Stacks

Instantiation of Template class

Module Contact: Dr Geoff McKeown, CMP Copyright of the University of East Anglia Version 2

Inheritance. Notes Chapter 6 and AJ Chapters 7 and 8

CISC-124. Passing Parameters. A Java method cannot change the value of any of the arguments passed to its parameters.

COMP200 - Object Oriented Programming: Test One Duration - 60 minutes

COMP 103. Mid Trimester Test 17 August 2006

University of Cape Town ~ Department of Computer Science. Computer Science 1015F ~ 2007

CMSC 132: Object-Oriented Programming II. Interface

Comparing Objects 3/28/16

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

CSC 1351: Quiz 6: Sort and Search

Abstract classes are used to define a class that will be used only to build new classes. No objects will ever be instantiated from an abstract class.

Lecture 20 SYS-1S22 / MTH-1A66. Sorting Objects. Stuart Gibson S01.09A. Sorting Arrays of Objects

CS 1302 Chapter 9 (Review) Object & Classes

Test 1: CPS 100. Owen Astrachan. October 1, 2004

Transcription:

QUEEN MARY, UNIVERSITY OF LONDON DCS128 ALGORITHMS AND DATA STRUCTURES Class Test Monday 27 th March 2006 11.05-12.35 Please fill in your Examination Number here: Student Number here: MODEL ANSWERS All answers to this test should be written on the test sheet, but you may use spare paper for rough working. Answer as many of the questions as you can. 1) In the space below explain how the selection sort algorithm works (you do not need to give Java code for it, but your explanation should be a complete description). Also explain why the selection sort algorithm is categorised as O(N 2 ). The selection sort algorithm is an algorithm for sorting in place, that is it changes the position of items in an indexable collection destructively (that is, changes their positions in the actual object, rather than creating a new object with the items in the different positions). It leaves the items in some sort of ordering, with no item added or removed from the collection. The algorithm is as follows. An index variable p is set up and at any point in the algorithm, the items in the collection before position p are in their final place where they will stay until the algorithm has finished, while the items at position p and after may have their position moved during the further execution of the algorithm. Initially p is set to 0, indicating that none of the collection has been sorted. Then, repeatedly, the lowest item in the ordering being used to sort is found in that part of the collection between that indexed by p up to the highest index. The item at that position is swapped in position with the item at position p. Then p can be increased by 1, since we know the item at position p is the lowest item from the rest of the collection and is in its correct sorted position. When p reaches one less than the size of the collection, we know the whole collection must be sorted. When we are sorting a collection, the main operation which takes place is the comparison of two items in the collection to check their ordering in the ordering being used to sort it. If the number of items in the collection is N, it can be seen that at first, N-1 comparisons are made to find the lowest item in the ordering in the whole collection. Then N-2 comparisons are made to find the lowest item in all of the collection except the first position, then N-3 comparisons to find the lowest item in all but the first two positions. This goes on until 1 position is made in the last pass of the final two items in the collection. So, it can be seen that the total number of comparisons made is (N-1)+(N-2)+(N-3)+ all the integers down to 1. We know this sums up to N 2 /2 comparisons. In the categorisation of algorithms in the big-o notation, we consider the number of main operations needed, ignoring constant multiplying factors, and considering only the highest term. So this means selection sort is categorised, by this reasoning, as of O(N 2 ). Algorithms and Data Structures Test 27 th March 2006 Page 1

2) The Java code library contains two generic classes, ArrayList<E> and LinkedList<E>. They appear to work quite similarly. In the space below, explain how they are related, and how they differ, and say why Java provides these two different classes. These are both classes that hold an indexable mutable collection of objects. They are generic classes, so they take a type argument (hence the <E> annotation) which gives the type of object they hold a collection of. Indexable means the collection these classes represent has the concept of items in it occurring in a particular position in the collection, given by an integer ranging from 0 to one less than the size of the collection (total number of items in it). The collections are mutable in two ways, firstly the item stored in a particular position may be changed, secondly items may be inserted at a particular position or removed from a particular position, causing items following them to be moved one place up or down in position. The common nature of ArrayList<E> and LinkedList<E> is fixed by both classes extending the interface type List<E>. This specifies all the operations necessary to give a mutable indexable collection type, and means ArrayList<E> and LinkedList<E> must necessarily provide those operations. The two classes differ in the data structure they use to implement their operations. The class ArrayList<E> uses an array and count data structure. This means that internally it has an array storing the items of the collection in the order they occur in the collection, but the array may be longer than the current size of the collection, so the count states how much of the array is currently used to represent the collection. An item is stored in the same position in the array as it is in the collection, so accessing an item at a particular position can be done in one step. The count is changed and items moved up or down positions in the array to implement those operations which add or remove items from the collection. The class LinkedList<E> uses a doubly-linked list data structure. This consists of cell objects each of which has two links to further cell objects, which are set so that one link points to the next item in the list, and the other points to the previous item in the list. The order of items in the doubly-linked list is the same as the order of items in the collection it represents. This means that accessing an item at a particular position involves following down the links in the list until that position is reached. Although this is inefficient compared to the one-step access of an item at a particular position in ArrayList<E>, adding or removing an item at a particular position in LinkedList<E> involves linking in a new cell but doesn t require changing the items stored in other cells, so that is more efficient than adding or removing an item from an ArrayList<E> object. Java provides both types in order to allow programmers to make a choice. In most cases, ArrayList<E> will be the type chosen to implement a mutable indexable list, but LinkedList<E> might be chosen if it is known that operations on the list objects will be mainly of the sort which LinkedList<E> implements more efficiently than ArrayList<E>. Algorithms and Data Structures Test 27 th March 2006 Page 2

3) a) Explain briefly how a static method in Java differs from an object method. A static method is not called on an object, and operates only on values passed to it as arguments through its parameters. An object method must always be called attached to an object (except when it is called inside another object method, in which case if it is not attached to another object, it is assumed attached to the same object as that method call is attached to). An object method call has access not only to the values passed to it as arguments to its parameters, but also to the variables inside the object it is called on. b) Explain briefly the two uses of the keyword this in Java. One use is as a method call on the first line of a constructor. In this case it has the effect of calling the code in another constructor in the same class whose number and type of parameters match the arguments to the call of this to set variables in the new object being constructed. The other, and main use of the keyword this, is that in any object method the word this means the object this method is being called on. c) Explain what is meant by dynamic binding when a method is called in Java. In Java, a variable may be set to refer to an object of a class which extends the class the variable is declared to be of. In that case, given a variable which refers to an object, the apparent type of the object is the type the variable is declared to be of, while the actual type is the type of the constructor used to create the object. It is possible the actual type contains code for a method which overrides a method in the apparent type (that is, has same name and number and types of parameters). If code indicates a method being called on a variable, when the program is executed the code for that method call is the code of the actual type rather than the apparent type. This principle is known as dynamic binding, because the actual type of a variable may only be known when the program is actually running. d) Explain what is meant by the natural ordering of a class of objects in Java. The natural ordering of a class of objects is the ordering which is given by the compareto object method which is in that class, or which it inherits. If obj1 and obj2 refer to two objects of that class, then the call of obj1.comparesto(obj2) returns 0 if they are considered equal in their natural ordering, a negative integer if obj1 is considered less than obj2 in their natural ordering, and a positive integer if obj1 is considered greater than obj2 in their natural ordering. Algorithms and Data Structures Test 27 th March 2006 Page 3

4) Consider the following three Java classes which form part of a program for a fantasy world game: class Being protected int strength; public Being(int s) strength=s; public int getstrength() return strength; public String tostring() return strength+ strength being ; class Monster extends Being private String colour; private int legs; public Monster(int s,int l,string c) super(s); legs=l; colour=c; public String tostring() return colour+ +legs+ -legged monster ; class Hero extends Being private Weapon holds; private String name; public Hero(int s,string nm,weapon w) super(s); holds=w; name=nm; public int getstrength() return strength+holds.getpower(); public String tostring() return name+ holding +holds; public void pickup(weapon w) holds=w; Question continued on next page Algorithms and Data Structures Test 27 th March 2006 Page 4

Suppose we have variables h of type Hero, m of type Monster, w of type Weapon, b of type Being, ab of type ArrayList<Being>, am of type ArrayList<Monster>, strs of type String[] and n of type int. For each of the following code fragments, say whether it is valid or invalid (where invalid code is code which would cause a Java compiler error): Valid/Invalid a) h.pickup(w); Valid (a) b) b=h; Valid (b) c) if(h.getstrength()>m.getstrength()) System.out.println(h); Valid (c) d) ab.remove(m); Valid (d) e) for(int i=0; i<am.size(); i++) System.out.println(am.get(i)); Valid (e) f) m=b; Invalid (f) g) for(int i=0; i<n; i++) am.add(new Monster( green )); Invalid (g) h) for(int i=0; i<n; i++) ab.add(new Hero(10,strs[i],w)); Valid (h) i) ab=am; I nvalid (i) j) am=ab; Invalid (j) k) m=am.get(n); Valid (k) l) n=am.remove(m); Invalid (l) m) m=am.remove(n); Valid (m) n) for(int i=0; i<ab.size(); i++) am.add(ab.get(i)); Invalid (n) o) for(int i=0; i<am.size(); i++) ab.add(am.get(i)); Valid (o) p) for(int i=0; i<ab.size(); i++) strs[i]=ab.get(i).tostring(); Valid (p) q) if(am.get(n)) System.out.println( Got monster +n); Invalid (q) r) if(ab.get(n) instanceof Hero) ab.get(n).pickup(w); Invalid (r) s) h = (Hero) (ab.get(n)); Valid (s) t) w = (Weapon) (strs[n]); Invalid (t) Note, this question will be marked on the basis of 1 mark for each correct answer, -1 mark for each incorrect answer. Algorithms and Data Structures Test 27 th March 2006 Page 5

5) This question uses the same code that was used for question 4). a) Write a static method which takes an ArrayList of Hero or Monster objects, and returns a reference to whichever object in the ArrayList is the strongest (i.e. returns the highest value when getstrength is called on it). static <T extends Being> T strongest(arraylist<t> a) T strongestsofar = a.get(0); for(int i=1; i<a.size(); i++) T next = a.get(i); if(next.getstrength()>strongestsofar.getstrength()) strongestsofar=next; return strongestsofar; b) Write a method exchange to go inside class Hero which works such that if h1 and h2 are two variables referring to objects of type Hero, calling h1.exchange(h2) will cause the objects to swap the values of their holds variables. void exchange(hero h) Weapon temp = this.holds; this.holds = h.holds; h.holds = temp; c) Write a method equals to go inside class Monster which overrides the default equals method, so that if m1 and m2 are two variables referring to objects of type Monster, m1.equals(m2) will return true if both objects have an equal strength variable, an equal legs variable and an equal colour variable, and false otherwise. boolean equals(object obj) if(!(obj instanceof Monster)) return false; Monster m = (Monster) obj; return this.legs==m.legs&& this.strength==m.strength&& this.colour.equals(m.colour); Algorithms and Data Structures Test 27 th March 2006 Page 6