LUNDS TKNISKA HÖGSKOLA 1(5) Institutionen för datavetenskap Tentamen, DAA30 Programmering i Java fortsättningskurs 2017 01 09, 8.00 13.00 Anvisningar: Denna tentamen består av 4 uppgifter. Preliminärt ger uppgifterna 1. 1 + 2.5 + 1.5 + 3 + 4 = 12 p 2. 4 + 7 = 11 p 3. 5 + 3 = 8 p 4. 5 p Tillåtet hjälpmedel: Java snabbreferens. För full poäng ska dina lösningar inte vara onödigt ineffektiva. I slutet av tentamen finns dokumentation av någon/några klasser och interface i Java Collections Framework. När rättningen är klar meddelas detta på kursens hemsida (cs.lth.se/edaa30). 1. a) Betrakta följande klasser: public class A { public void method() { System.out.println("a"); public class B extends A { public void method() { System.out.println("b"); Vad händer när följande rader exekveras? Motivera ditt svar. A ref = new B(); ref.method(); b) Betrakta följande algoritm: int sum = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == j) { sum += m[i][j]; Vad blir tidskomplexiteten för summeringen ovan angivet i ordo-notation? Antag att man mätt exekveringstiden för ovanstående rader för n = 200000 och fått en tid på 30 ms. Ungefär hur lång tid blir exekveringstiden för för n = 1000000? Kan summeringen göras på ett effektivare sätt? Motivera dina svar.
2(5) c) Antag att följande sekvenser sätts in i ett tomt, icke balanserat binärt sökträd. Vilken eller vilka av sekvenserna ger ett balanserat träd (AVL-träd). Rita det eller de träd som blir balanserade. 12, 20, 8, 15, 2, 9, 25 5, 3, 10, 8, 12, 7 10, 12, 15, 19, 21, 25, 16 10, 5, 7, 2, 17, 25, 1 d) Vad innebär en kollision i en öppen hashtabell? Vilka faktorer påverkar antal kollisioner och hur kan man minska risken för kollisioner? e) lementen i en vektor ska sorteras i stigande ordning. Vilka av följande sorteringsalgoritmer påverkas tidsmässigt av att indata råkar bestå av en vektor med element i avtagande ordning? Motivera dina svar genom att för var och en av de fyra sorteringsalgoritmerna beskriva hur de påverkas. 1. Urvalssortering (eng. Selection sort) 2. Insättningssortering (eng. Insertion sort) 3. Quicksort (med pivot = medianen av första, mittersta och sista elementet) 4. Heapsort (med maxheap) 2. a) Denna uppgift handlar om att skriva en klass ScoreBoard som håller reda på spelare och deras resultat. Klassen är tänkt att användas i ett program för en webbsajt som låter personer spela brädspel över nätet. tt resultat beskrivs av klassen Result: public class Result { private String userid; private int points; * Skapar ett resultat med points poäng för spelaren med användarnamnet userid. public Result(String userid, int points) { this.userid = userid; this.points = points; * Returnerar antal poäng. * @return antal poäng public int getpoints() { return points; * Returnerar användarnamnet. * @return användarnamnet public String getuserid() { return userid; public String tostring() { return userid + " " + points;
3(5) Implementera klassen ScoreBoard som ska innehålla följande två metoder: * Tar reda på bästa resultatet för spelaren userid. Om spelaren inte har * något resultat ska null returneras. * @param userid spelarens användarnamn * @return bästa resultatet för spelaren userid public Result getresult(string userid) {... * Uppdaterar resultatet för spelaren userid. Om spelaren sedan tidigare har * ett resultat ska det bara uppdateras om den nya poängen är högre än den * tidigare. * @param res det nya resultatet public void updatepoints(result res) {... Ledning och anvisningar: För varje spelare är det bara hittills bästa resultat (det med högst poäng) som lagras. Använd en klass som implementerar java.util.map för att hålla reda på spelarna och deras bästa resultat. b) Lägg till följande metod i klassen ScoreBoard: * Returnerar en lista med de k bästa resultaten. Om k är större än antal inlagda * resultat ska listan innehålla alla resultat. * @return en lista med de k bästa resultaten * @param k max antal resultat som ska returneras * @throws IllegalArgumentxception om k är mindre än 1 public List<Result> gethighestscores(int k) {... Ledning och anvisningar: Följande algoritm ska användas: Sätt in de k första resultaten i en prioritetskö För de övriga resultaten r om r har högre poäng än sämsta resultatet i prioritetskön byt ut det sämsta resultatet mot r Algoritmen går alltså ut på att i en prioritetskö hålla reda på de k hittills bästa resultaten bland de man gått igenom. fter genomgången innehåller prioritetskön de k bästa resultaten. Använd klassen java.util.priorityqueue. Beroende på hur metoden gethighestscores implementeras kan det behövas ändringar/tillägg i övriga koden. Gör dessa i så fall. Resultatslistan ska ordnas efter avtagande poäng. Resultatslistan ska innehålla max k element. Om flera resultat har samma poäng kanske vissa av dessa kommer med i slutet av listan och andra inte. I så fall kvittar det vilka av resultaten med lika poäng som kommer med i listan.
4(5) 3. a) I den här uppgiften ska du arbeta med en klass BoundedMaxList som skulle kunna ha använts istället för algoritmen och prioritetskön i förra uppgiften. Listan innehåller max k element. Om ett element läggs till när listan är full ska det minsta elementet tas bort. Din uppgift är att implementera metoden add. public class BoundedMaxList< extends Comparable<? super >> { private int maxnbr; private int size; private Node<> first; * Skapar en lista som kan innehålla max k element. * @param k listans maximala storlek public BoundedMaxList(int k) { maxnbr = k; * Lägg till elementet e i listan. Om listan blir för stor ska minsta * elementet tas bort. * @param e elementet som ska läggas till i listan public void add( e) { // Lägg till egen kod här private static class Node<> { private data; private Node<> next; public Node( data) { this.data = data; next = null; Ledning och anvisningar: Listan ska vara en enkellänkad lista bestående av sammanlänkade Node-objekt. Listan ska hållas sorterad i stigande ordning. b) Skugga metoden tostring i klassen BoundedMaxList. Den sträng som returneras ska innehålla elementen i listan i omvänd (dvs. avtagande) ordning. fter varje element ska radslut ( \n ) finnas. Rekursiv tekniks ska användas.
5(5) 4. Klassen mployee (se nedan) beskriver en anställd. Vissa av de anställda är också chefer som basar över 0 till flera anställda som i sin tur kan vara chefer eller vanliga anställda (se fig. 1). Cheferna beskrivs av subklassen Manager. Manager Manager Manager Manager mployee mployee mployee Manager mployee mployee mployee mployee Figur 1: Hierarki med chefer och övriga anställda. public class mployee { protected String name; protected int salary; public mployee(string name, int salary) { this.name = name; this.salary = salary; public String getname() { return name; public class Manager extends mployee { private List<mployee> staff; public Manager(String name, int salary) { super(name, salary); staff = new ArrayList<mployee>(); public void addstaff(mployee e) { staff.add(e); Din uppgift är att lägga till kod som med rekursiv teknik beräknar den totala lönesumman för anställda. Med den totala lönesumman menas här den egna lönen plus summan av eventuella underställdas löner. Lös uppgiften genom att lägga till en metod int gettotalsalary() i klassen mployee och skugga denna metod i subklassen Manager.
java.lang Interface Iterable<T> Type Parameters: T - the type of elements returned by the iterator Modifier and Type Method and Description Iterator<T> iterator() Returns an iterator over a set of elements of type T. java.util Interface Iterator<> Type Parameters: - the type of elements returned by this iterator Methods Modifier and Type Method and Description boolean hasnext() Returns true if the iteration has more elements. next() Returns the next element in the iteration. void remove() Removes from the underlying collection the last element returned by this iterator (optional operation). java.lang Interface Comparable<T> Type Parameters: T - the type of objects that this object may be compared to Modifier and Type Method and Description int compareto(t o) Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object. java.lang Interface Comparator<T> Type Parameters: T - the type of objects that may be compared by this comparator Modifier and Type Method and Description int compare(t o1, T o2) Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
java.util!interface Map<K,V> Type Parameters: K - the type of keys maintained by this map V - the type of mapped values All Known Implementing Classes: AbstractMap, Attributes, AuthProvider, ConcurrentHashMap, ConcurrentSkipListMap, nummap, HashMap, Hashtable, IdentityHashMap, LinkedHashMap, PrinterStateReasons, Properties, Provider, RenderingHints, SimpleBindings, TabularDataSupport, TreeMap, UIDefaults, WeakHashMap An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value. Method Summary void clear() Removes all of the mappings from this map (optional operation). boolean containskey(object key) Returns true if this map contains a mapping for the specified key. boolean containsvalue(object value) Returns true if this map maps one or more keys to the specified value. Set<Map.ntry<K,V>> entryset() Returns a Set view of the mappings contained in this map. boolean equals(object o) Compares the specified object with this map for equality. V get(object key) Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key. int hashcode() Returns the hash code value for this map. boolean ismpty() Returns true if this map contains no key-value mappings. Set<K> keyset() Returns a Set view of the keys contained in this map. V put(k key, V value) Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for the key, the old value is replaced by the specified value. void putall(map<? extends K,? extends V> m) Copies all of the mappings from the specified map to this map (optional operation). V remove(object key) Removes the mapping for a key from this map if it is present (optional operation). Returns the value to which this map previously associated the key, or null if the map contained no mapping for the key. int size() Returns the number of key-value mappings in this map. Collection<V> values() Returns a Collection view of the values contained in this map. java.util Class HashMap<K,V> Hash table based implementation of the Map interface. Constructor Summary HashMap() Constructs an empty HashMap with the default initial capacity (16) and the default load factor (0.75). HashMap(int initialcapacity) Constructs an empty HashMap with the specified initial capacity and the default load factor (0.75). HashMap(int initialcapacity, float loadfactor) Constructs an empty HashMap with the specified initial capacity and load factor. HashMap(Map<? extends K,? extends V> m) Constructs a new HashMap with the same mappings as the specified Map. java.util Class TreeMap<K,V> A Red-Black tree. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used. Constructor Summary TreeMap() Constructs a new, empty tree map, using the natural ordering of its keys. TreeMap(Comparator<? super K> comparator) Constructs a new, empty tree map, ordered according to the given comparator. TreeMap(Map<? extends K,? extends V> m) Constructs a new tree map containing the same mappings as the given map, ordered according to the natural ordering of its keys. TreeMap(SortedMap<K,? extends V> m) Constructs a new tree map containing the same mappings and using the same ordering as the specified sorted map. java.util!interface Map.ntry<K,V> A map entry (key-value pair). Method Summary boolean equals(object o) Compares the specified object with this entry for equality. K getkey() Returns the key corresponding to this entry. V getvalue() Returns the value corresponding to this entry. int hashcode() Returns the hash code value for this map entry.
java.util Class PriorityQueue<> Type Parameters: - the type of elements held in this collection An unbounded priority queue based on a priority heap. The elements of the priority queue are ordered according to their natural ordering, or by a Comparator provided at queue construction time, depending on which constructor is used. A priority queue does not permit null elements. A priority queue relying on natural ordering also does not permit insertion of non-comparable objects (doing so may result in ClassCastxception). The head of this queue is the least element with respect to the specified ordering. If multiple elements are tied for least value, the head is one of those elements -- ties are broken arbitrarily. The queue retrieval operations poll, remove, peek, and element access the element at the head of the queue. Constructor Summary Constructor and Description PriorityQueue() Creates a PriorityQueue with the default initial capacity (11) that orders its elements according to their natural ordering. PriorityQueue(Collection<? extends > c) Creates a PriorityQueue containing the elements in the specified collection. PriorityQueue(Comparator<? super > comparator) Creates a PriorityQueue with the default initial capacity and whose elements are ordered according to the specified comparator. PriorityQueue(int initialcapacity) Creates a PriorityQueue with the specified initial capacity that orders its elements according to their natural ordering. PriorityQueue(int initialcapacity, Comparator<? super > comparator) Creates a PriorityQueue with the specified initial capacity that orders its elements according to the specified comparator. PriorityQueue(PriorityQueue<? extends > c) Creates a PriorityQueue containing the elements in the specified priority queue. Method Summary Modifier and Type Method and Description boolean add( e) Inserts the specified element into this priority queue. Returns true if the element was added to this queue, else false void clear() Removes all of the elements from this priority queue. Comparator<? super > comparator() Returns the comparator used to order the elements in this queue, or null if this queue is sorted according to the natural ordering of its elements. boolean contains(object o) Returns true if this queue contains the specified element. More formally, returns true if and only if this queue contains at least one element e such that Iterator<> o.equals(e). iterator() Returns an iterator over the elements in this queue. boolean offer( e) Inserts the specified element into this priority queue. Returns true if the element was added to this queue, else false peek() Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty. poll() Retrieves and removes the head of this queue, or returns null if this queue is empty. boolean remove(object o) Removes a single instance of the specified element from this queue, if it is present. More formally, removes an element e such that o.equals(e), if this queue contains one or more such elements. Returns true if and only if this queue contained the specified element (or equivalently, if this queue changed as a result of the call). int Object[] size() Returns the number of elements in this collection. toarray() Returns an array containing all of the elements in this queue. The elements are in no particular order. <T> T[] toarray(t[] a) Returns an array containing all of the elements in this queue; the runtime type of the returned array is that of the specified array. The returned array elements are in no particular order. If the queue fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this queue.!
Interface List<> Type Parameters: - the type of elements in this list Java Platform Standard d. 7 All Superinterfaces: Collection<>, Iterable<> Known Implementing Classes: AbstractList, ArrayList LinkedList public interface List<> extends Collection<> An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list. Unlike sets, lists typically allow duplicate elements. Method Summary Methods Modifier and Type Method and Description boolean add( e) Appends the specified element to the end of this list (optional operation). void add(int index, element) Inserts the specified element at the specified position in this list (optional operation). boolean addall(collection<? extends > c) Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator (optional operation). boolean addall(int index, Collection<? extends > c) Inserts all of the elements in the specified collection into this list at the specified position (optional operation). void clear() Removes all of the elements from this list (optional operation). boolean contains(object o) Returns true if this list contains the specified element. boolean containsall(collection<?> c) Returns true if this list contains all of the elements of the specified collection. boolean equals(object o) Compares the specified object with this list for equality. int get(int index) Returns the element at the specified position in this list. hashcode() Returns the hash code value for this list. int indexof(object o) Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. boolean Iterator<> ismpty() Returns true if this list contains no elements. iterator() Returns an iterator over the elements in this list in proper sequence. int lastindexof(object o) Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element. ListIterator<> listiterator() Returns a list iterator over the elements in this list (in proper sequence). ListIterator<> listiterator(int index) Returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list. remove(int index) Removes the element at the specified position in this list (optional operation). boolean remove(object o) Removes the first occurrence of the specified element from this list, if it is present (optional operation). boolean removeall(collection<?> c) Removes from this list all of its elements that are contained in the specified collection (optional operation). boolean retainall(collection<?> c) Retains only the elements in this list that are contained in the specified collection (optional operation). int List<> Object[] set(int index, element) Replaces the element at the specified position in this list with the specified element (optional operation). size() Returns the number of elements in this list. sublist(int fromindex, int toindex) Returns a view of the portion of this list between the specified fromindex, inclusive, and toindex, exclusive. toarray() Returns an array containing all of the elements in this list in proper sequence (from first to last element). <T> T[] toarray(t[] a) Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array.