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-05-16 i A-huset. Tillåtna hjälpmedel: Inga. Kurskod SMD135/167 Datum 2005-05-06 Skrivtid 4 tim Bilagor: Klassen Vector. 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) Skriv en rekursiv metod. b) Skriv en metod som använder iteration. c) 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? d) Vad skrivs ut av detta C-program? main(){ char s[] = "CSEE"; /* 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 */ e) Vad betyder attributet static då det används vid deklarationen av en variabel? (Förklara gärna med ett exempel om du vill.) a) Write a recursive method. b) Write a method that makes use of iteration.
G L I T V R E Figure 1: A binary tree. c) 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? d) What is the output when the following program is run? main(){ char s[] = "CSEE"; /* 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 */ 2. Theory e) What does the attribute static mean when it occurs in the declaration of a variable? (Use an example to explain, if you like.) a) Vad är en dubbellänkad lista och vad är poängen med sådana jämfört med enkellänkade listor? b) Nämn en sorteringsalgoritm vars asymptotiska tidskomplexitet är O(n log n) i medelfallet. c) Binärsökning är ett effektivt sätt att söka efter data i en array, men under vilka förutsättningar? d) I vilket ordning besöks noderna om man går igenom det binära trädet i figur 1 i postorder-ordning?
e) Vad är det som efterfrågas i Handelsresandeproblemet (Traveling Salesman Problem)? a) What is a doubly-linked list, and what is the point of such a list compared with singly-linked lists? b) Give an example of a sorting algortihm that has a time complexity of O(n log n) in the average case. c) Binary search is an effective method to search through an array, but under which circumstances? d) In which order are the nodes visited in if the tree in Figure 1 is traversed in postorder-ordering? e) What is asked for in the Traveling Salesman Problem? 3. Inheritance and Exceptions BankRoll +sum(): int +colours(): Vector +add(c:chip): void +num(colour:string): int +remove(colour:string): void Chip +denomination(): int +colour(): String #change_denomination(denom:int): void RedChip BlueChip BlackChip Figure 2: UML diagram for Problem 3. I ett pokerspelsprogram hanteras bland annat olika sorters spelmarker. Varje sort har en viss färg (en sträng) och valör (ett heltal). Valören hos en sorts spelmarker (dvs alla de enskilda spelmarker som finns av den sorten) kan ändras under spelets gång. Färgen är däremot fix. Skriv följande baserat på figur 2: (a) Den abstrakta klassen Chip för ett slags spelmarker. Denna deklarerar de abstrakta metoderna denomination som ger tillbaka en spelmarkers valör och colour som ger tillbaka en spelmarkers färg samt den konkreta (ickeabstrakta) statiska metoden change_denomination som ändrar valören på ett slags spelmarker (alla existerande spelmarker av den sorten ändrar valör). (b) Klasserna RedChip, BlueChip, BlackChip som alla ärver Chip och vars objekt (enskilda spelmarker) är röda, blå respektive svarta och till att börja med har valörerna 5, 10 respektive 100. (c) Klassen BankRoll som håller reda på en (1) spelares hög med spelmarker och tillhandahåller följande metoder: sum, som ger totala summan av alla spelmarker i högen. colours som ger tillbaka en referens till en Vector med alla de färger som åtminstone en spelmarker i högen har. Klassen Vector (från Java s API) finns bifogad. add som lägger till en spelmarker till högen.
num som ger tillbaka antalet spelmarker i högen som har en viss färg. remove som tar bort en spelmarker av given färg från högen. Om det saknas sådana marker ska programmet kasta ett exception NoSuchElementException. Du får anta att detta exception redan finns deklarerat och kan användas. Tips: En hög som den ovan (en bank roll ) kan t ex representeras med en Vector. In a poker program there is a need to handle poker chips. Each kind of chip has a certain colour (a string) and a denomination (an int). The denomination of a kind of chips (all red chips, for instance) can change. The colour is, however, fixed. Write the following based on Figure 2: (a) The abstract class Chip that represents a general kind of chip. This class declares the abstract methods denomination that returns the current denomination of a chip and colour that returns the colour of a chip. It also contains the concrete (non-abstract) and static method change_denomination that change the denomination of a kind of chips (the result is that all chips of the same colour change their denomination at the same time). (b) The classes RedChip, BlueChip, BlackChip who all extends Chip. Their colours are red, blue and black respectively. To start with their denominations are 5, 10, and 100 respectively. (c) The class BankRoll that keeps track of the pile of chips one (1) player has. It contains the following methods: sum that gives as result the total sum of all chips in the pile. colours that gives back a reference to a Vector-object that holds each colour that at least one chip in the pile has. (Recall that colours are strings.) The class Vector (from the Java API) can be found in the last part of the exam. add that adds a chip to the pile. num that gives as result the total number of chips in the pile of a certain colour. remove that removes one chip of a certain colour from the pile. If there are no chips of the given colour, the exception NoSuchElementException should be thrown. You can assume that the class that represent the exception has already been written. Hint: A pile can be represented as a Vector. 4. Song competition I en melodifestival ingår det ett antal bidrag, som alla kan få poäng. Din uppgift är att skriva en klass som representerar melodifestivaler. Konstrueraren ska ta ett heltal som argument som anger hur många bidrag som ingår i festivalen. Tillför metoden void givepoints(int song, int points) som ger points antal poäng till bidrag nummer song. Bidragen numreras så att det första bidraget får nummer ett, det andra nummer två och så vidare. Du får anta att man aldrig försöker ge poäng till ett bidrag som inte finns. Tillför även metoden int leader() som returnerar numret på det bidrag som har mest poäng. Om flera bidrag har högst poäng får vilket som helst av de bidragen returneras.
Tillför slutligen metoden int amountofpoints() som returnerar hur många poäng som totalt delats ut till alla bidrag i alla melodifestivaler som skapats. A song competition can be said to contain a number of songs, where every song can be awarded points. Your task is to write a class that represents a song competition. The constructor should take an integer as an argument, which specifies the number of songs in the competition. Write the method void givepoints(int song, int points) that gives points number of points to song number song. The songs are numbered so that the first song has number one, the second song has number two and so on. You do not have to consider the case when one tries to give points to a song that does not exist. Also, write the method int leader() that returns the number of the song with the highest number of points. If several songs all have the highest number of points it is ok to return the number of anyone of those songs. Finally, write the method int amountofpoints() that returns the total number of points that has been given to all songs in all song competitions. 5. Can t see the forest for all the trees Skriv en klass BinaryNode som representerar en nod i ett binärt träd. Varje nod kan ha noll, ett, eller två barn, som även de är binära noder. Skriv en metod int height() som returnerar höjden på ett träd som noden är rot i. Om noden saknar barn (vilket betyder att det är ett löv) är höjden 1. Skriv även metoden int size() som returnerar antal noder i det träd noden är rot i. Write a class BinaryNode that represents a node in a binary tree. Every node can have zero, one, or two children, that themselves are binary nodes as well. Write the method int height() that returns the height of the tree that the node in question is the root of. If the node has no children (and therefore is a leaf) the height is 1. Also write the method int size() that returns the number of nodes in the tree that the node in question is the root of. 6. Grammarrays I Java kan man, för att deklarera samt initialisera en heltalsarray, till exempel skriva int[] a = {1,3,5,7; Din uppgift är att, med hjälp av tokenizern i appendix A, skriva en parser som undersöker huruvida en sträng beskriver en heltalsarray, dvs huruvida den följer reglerna fˆr grammatiken; <array> = "{" <array > "" <array > = <num> <array > <array > = "," <num> <array > empty In Java it is possible to declare and initialize an integer array by writing, for example, int[] a = {1,3,5,7;
Your task is to, using the tokenizer in appendix A, write a parser that checks whether a string describes an integer array, or in other words, if it follows the rules of the following grammar: <array> = "{" <array > "" <array > = <num> <array > <array > = "," <num> <array > empty public abstract class ArrayDescription { private static Tokenizer token ; public static boolean accept ( Reader input ){ boolean ok ; token = new Tokenizer ( input ) ; token. get ( ) ; ok = ad ( ) ; return ok ; private static boolean ad (){ // add your code here. Listing 1: ArrayDescription.java
A Tokenizer.java import java. io. ; public class Tokenizer { private StreamTokenizer tokens ; protected i nt type ; public static final int ID = 1, NUMBER = 2, RIGHTPAREN = 3, LEFTPAREN = 4, ENDOFFILE = 5, PLUS = 6, MINUS = 7, ASTR = 8, SLASH = 9, LEFTBRACE = 10, RIGHTBRACE = 11, COMMA = 12, ILLEGAL = 1; public Tokenizer ( Reader input ) { tokens = new StreamTokenizer ( input ) ; tokens. ordinarychar ( ) ; tokens. ordinarychar ( / ) ; public void get () { try {type = tokens. nexttoken ( ); catch ( IOException e ) {throw new RuntimeException ( e. tostring ( ) ) ; public int kind () { switch ( type ) { case Str ea mto kenizer.tt WORD : return ID ; case Str ea mto kenizer.tt NUMBER : return NUMBER; case Str ea mto kenizer. TT EOF : return ENDOFFILE; default : switch ((char) type ) { case ( : return LEFTPAREN; case ) : return RIGHTPAREN; case + : return PLUS; case : return MINUS; case : return ASTR; case / : return SLASH; case { : return LEFTBRACE; case : return RIGHTBRACE; case, : return COMMA; default : return ILLEGAL; public String ident () {return tokens. sval ; public double numbervalue () {return (double) tokens. nval ; public String tostring () {return tokens. tostring ( ); Listing 2: Tokenizer.java