LULEÅ TEKNISKA UNIVERSITET Tentamen i Program och datastrukturer, Objektorienterad design Totala antalet uppgifter: 5 Lärare: Håkan Jonsson och Tomas Johansson (1700, 1465) Resultatet anslås senast 2005-03-24 i A-huset. Tillåtna hjälpmedel: Inga. Kurskod SMD135/167 Datum 2005-03-16 Skrivtid 4 tim Bilagor: inga. Varje uppgift ges först på svenska och sen på engelska. Eventuella exempel återfinns alltid sist i uppgiften och då endast på engelska. Tänk noga efter vad som ska döljas respektive vara synligt utanför klassen. Var noga med att objekts inre tillstånd inte exponeras så att de kan förändras utifrån där det inte är lämpligt. 1. Some Issues in Programming a) Klassen A innehåller den publika metoden x(). Klassen B ärver A och innehåller en ny deklaration av x(). Klassen C ärver sen B och innehåller även den en ny deklaration av x(). Samtliga deklarationer av x() har samma typsignatur. Om nu ett program innehåller deklarationen B b = new C(); är det då metoden x() i A, B eller C som anropas då satsen b.x(); utförs? b) Vad skrivs ut av detta C-program? main(){ char s[] = "lost"; /* create a string */ char c; char *p; c = s[2]; /* move chars around */ p = &s[2]; --p; s[0] = c; printf("%s\n",s); /* print the string */ c) Det finns 4 synlighetsattribut i Java: private, public, protected samt ett underförstått attribut man inte skriver ut. Vilket används för variabler som representerar en abstrakt datatyps inre tillstånd? d) En kulpyramid med höjden n består av en kvadratisk botten med n 2 kulor på vilken det står en kulpyramid med höjden n 1. En kulpyramid med höjden 1 består av 1 kula. Skriv en rekursiv metod i Java som beräknar totala antalet kulor i en kulpyramid som har höjden n. (2p)
a) The class A contains the public method x(). The class B inherits A and contains a new declaration of x(). The class C inherits B and does also contain a declaration of x(). All declarations of x() have the same type signature. If a program contains the declaration B b = new C(); and the statement b.x(); is executed, is it then the method x() i A, B, or C that is invoked? b) What is the output when the following program is run? main(){ char s[] = "lost"; /* create a string */ char c; char *p; c = s[2]; /* move chars around */ p = &s[2]; --p; s[0] = c; printf("%s\n",s); /* print the string */ c) There are 4 scope attributes in java: private, public, protected and another one that is implicit when no attribute is given. Which one is used for variables that represent the inner state of an abstract data type? d) A pyramid of height n consists of a quadratic bottom with n 2 pebbles on which a pyramid of height n 1 stands. A pyramid of height 1 consists of a single pebble. Write a recursive method in Java that computes the total number of pebbles in a pyramid of height n. (2p) 2. Theory a) Vad är den asymptotiska övre gränsen på antalet steg algoritmen Selection Sort tar för att sortera n tal i värsta fall? b) Vad är en hashtabell och vad är poängen med en sådan? c) Vilken egenskap måste ett binärt träd ha för att kunna vara en heap? d) Förklara varför det är en fördel om binära sökträd är balanserade? e) Nämn ett problem som är oavgörbart och som därför saknar lösning. a) What is the asymptotical upper bound on the number of steps Selection Sort takes to sort n numbers? b) What is a hash table, and what is the major point of hash tables? c) What property is a binary tree required to have in order to be a heap? d) Explain why it is an advantage if binary search trees are balanced. e) Name an undecidable problem that lacks solutions. 3. Game scores (5p)
Skriv en Javaklass GameScore vars objekt håller reda på poängställningen i en match mellan två lag där ett är hemmalag och ett bortalag. Poängställningen är 0-0 när ett objekt skapas (dvs en match startar) och ska kunna ökas med en poäng i taget via två metoder inchometeam() och incvisitingteam(). Nuvarande ställning ska ges av metoden currentscore() som ger tillbaka en sträng med hemmalagets poäng, ett bindestreck och bortalagets poäng. Det kan spelas flera matcher samtidigt och man ska kunna få det genomsnittliga antalet mål per match genom ett anrop till metoden statistics(). Tips: Adderar man ett heltal till en sträng får man en sträng. Write a Java class GameScore that keeps track of the score in a game between a home team and a visiting team. The score is 0-0 when an object is created (and a game starts) and is increased one point at a time by calling inchometeam() and incvisitingteam() respectively. The currect score should be returned by a method currentscore() and in the form of a string containing the points of the home team, a dash, and the points of the visiting team. Several games could be played at the same time and a call to the methodstatistics() should give the average number of points made per match as result. Hint: If you add an integer to a string, you get a string. 4. Priority Queue (5p) Din uppgift är att skriva en prioritetskö. Uppgiften består av två delar. a) Implementera ett gränssnitt för prioritetsköer. Det ska innehålla följande metoder: insert, som tar som argumnet ett Object och dess prioritet (i form av ett double) och sätter in det i kön. first, som returnerar det objekt i kön som har högst prioritet. removefirst, som tar bort objektet med högst prioritet från kön. b) Skriv en klass för prioritetsköer som implementerar gränssnittet från uppgift a. Internt ska kön representeras som en länkad lista, med hjälp av den bifogade nodklassen. Nodklassen ska vara en intern klass i kön. Metoderna first och removefirst ska ta konstant tid oberoende av storleken på kön. Förenkling: Du kan anta att metoderna first och removefirst aldrig används när prioritetskön är tom, dvs du behöver inte kontrollera om det finns något objekt att returnera/ta bort. (4p) Your task is to write a priority queue. The task consists of two parts. a) Write an interface for priority queues. It should contain the following methods: insert, that takes as arguments an Object and its priority (in the form of a double) and inserts it into the queue. first, that returns the object in the queue with the highest priority. removefirst, that removes the object with the highest priority from the queue. b) Write a priority queue class that implements the interface from part a. The queue should be represented internally as a linked list, with the help from the included Node class. The node class should be an internal class in the queue.
The methods first and removefirst should take constant time to execute regardless of the size of the queue. Simplification: You can assume that the methods first and removefirst never are used on an empty queue, i.e. you do not need to check if there exists an object to return/remove. (4p) private class Node{ double priority; Object data; Node next; public Node(double priority, Object data, Node next){ this.priority = priority; this.data = data; this.next = next; 5. Inheritance and Exceptions (5p) Customer +Customer(name:String,amount:int,:) +getid(): int +spend(amount:int) BrokeException throws VIPCustomer +VIPCustomer(name:String,amount:int) +spend(amount:int) FancyCustomer +FancyCustomer(name:String,amount:int) Figure 1: UML diagram for Problem 5. Acme Programmings kösimulator floppade totalt i förra årets julhandel. Många tror att det kan bero på att produkten inte släpptes förrän i februari, men cheferna är övertygade om att anledningen var att representationen av kunderna var alldeles för enkel. Din uppgift är att skriva nya klasser som representerar kunder, enligt följande anvisningar: Klassen Customer representerar en kund. Varje kund har ett ID-nummer, ett namn, och en viss summa pengar. Varje ny kund som skapas får automatiskt ett ID-nummer i form av ett heltal, som är ett större än den föregående kundens ID-nummer. Den första kunden som skapas får ID-numret 0. Metoden getid() ska returnera kundens ID-nummer. Konstrueraren tar två argument: kundens efternamn och kundens förmögenhet. Metoden spend(int amount) innebär att kunden handlar något för en viss summa, vilket förstås betyder att kundens förmögenhet ska minska med motsvarande summa. Om amount är större än kundens förmögenhet ska kundens förmögenhet sättas till 0 och undantaget BrokeException kastas. Du får anta att klassen som representerar undantaget redan är skriven. Klassen VIPCustomer, som utökar Customer, representerar kunder med kontakter. De behöver aldrig betala: när spend-metoden för en sådan kund utförs ska kundens förmögenhet inte påverkas, utan allt som händer är att texten Jag känner faktiskt ägaren! ska skrivas ut på skärmen.
Klassen FancyCustomer, som även den utökar Customer, representerar extremt fina kunder. När en FancyCustomer skapas ska namnet som skickas till konstrueraren ändras till adlig form, närmare bestämt ska von läggas till före namnet innan det lagras. Till exempel, om man i programmet skriver FancyCustomer fc = new FancyCustomer("Anka", 3000); ska kunden få namnet von Anka. Acme Programming s queue simulator sank without a trace in last year s christmas shopping. Some people believe it was because the product wasn t actually released until this February, but the management is convinced the reason is that the representation of the customers was far too simple. Your task is to write new classes that represents the customers, according to the following instructions: The class Customer represents a customer. Every customer has an ID number, a name, and a sum of money. Every new customer that is created automatically receives an ID number that is one unit bigger than the ID number of the last created customer. The first customer that is created receives the ID number 0. The method getid() returns the ID number of the customer. The constructor takes two arguments: the name of the customer and the amount of money the customer has. The method spend(int amount) represents that the customer buys something for a certain amount, which of course means that the customer s money should be reduced by the same amount. If the amount is more than what the customer can afford, the customer s money should be reduced to 0 and the exception BrokeException is thrown. You can assume that the class that represents BrokeException is already written. The class VIPCustomer, that inherits Customer, represents customers with connections. They never have to pay: when the spend-method for a VIPCustomer is executed the customer s money aren t affected, the only thing that happens is that the text I happen to know the owner! is printed to the screen. The class FancyCustomer, that also inherits Customer, represents very fancy customers. When a FancyCustomer is created the name that is passed to the constructor should be changed into a more noble form, to be exact von will be added in front of the name before it is stored. For example, the following code in the simulator FancyCustomer fc = new FancyCustomer("Smith", 3000); means that the customer s name will be von Smith.