CMPT 225 : Lab 5, Correction

public class Player extends Creature{ private Hashtable hT = new Hashtable();. /* …. Content of the class … */ public void writeData(int key, Object data){ ...
61KB taille 4 téléchargements 353 vues
CMPT 225 : Lab 5, Correction Heaps, sorting and hash tables I. Complete the Player (1 pt) In creature.player, you had two functions to complete. We want to write and retrieve data, and you had to back it up using a hash table. Thus, the result is: public class Player extends Creature{ private Hashtable hT = new Hashtable(); /* …. Content of the class … */ public void writeData(int key, Object data){ hT.put(key, data); } public Object readData(int key){ return hT.get(key); } } You also had to make sure that Philippe was using the writeData method, so you had to add a line in the talk method of creature.people.Philippe saying p.writeData(1, “whatever”). II. Complete creature.people.Awin (3 pts) public AbstractMap reward(Stack s){ HashMap hm = new HashMap(); // when you look in the Javadoc, you see which classes extend AbstractMap int money = s.size()*50; // we know that each customer pays 50$ so the amount of money is size*50 money *= 0.5; // we want to save half of the money so we already take it out while(!s.empty()){ // and then for each customer, from the last one to the first one money *= 0.5; // we give him half of the remaining. We have n/4 + n/8 + n/16 … → n/2 hm.put(s.pop(), ""+money); // to convert the money into a String just add "" before } // this should return the benefit after having rewarded the customers return hm; } III.

Complete creature.people.Helia (2 pts)

// a comparator is a class that implements Comparator of a certain object. By subtracting the two heights we know which // goblin is taller. You can also explicitly say “if ( o1.getHeight() > o2.getHeight() ) return …” and you get partial marks then. private class GoblinCmp implements Comparator{ public int compare(Goblin o1, Goblin o2) { return o1.getHeight() - o2.getHeight(); } }

// as we saw in class to sort students, if we want to use a comparator we need to get an instance of it private Comparator getComparator(){ return new GoblinCmp(); }

private Goblin[] goblinSort(Goblin[] array, Comparator cmp){ int i = 1, j = 2 ; // we said by e-mail that you had to use Gnome sort, and you can just get it from Wikipedia while (i < array.length){ if( cmp.compare(array[i-1], array[i])