Presentation is loading. Please wait.

Presentation is loading. Please wait.

Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington2012 More Collections: Queues,

Similar presentations


Presentation on theme: "Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington2012 More Collections: Queues,"— Presentation transcript:

1 Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington2012 More Collections: Queues, Maps COMP 103 #4 2012 T2

2 © Peter Andreae COMP 103 04:2 Menu More Collections Queues and applications Maps and applications Sets Notices: Tutorials this week Help desk and online help Assignments

3 © Peter Andreae COMP 103 04:3 Queues Queues are like lists, but constrained: Collection of values with an order Constrained access: Only remove from the front Two varieties: Ordinary queues: only add at the back Priority queues: add with a given priority

4 © Peter Andreae COMP 103 04:4 Queues Used for Operating Systems, Network Applications, multi-user systems Handling requests/events/jobs that must be done in order (often called a “buffer” in this context) Simulation programs Representing queues in the real world (traffic, customers, deliveries, ….) Managing the events that must happen in the future Search Algorithms Computer Games Artificial Intelligence Java provides a Queue interface several classes: LinkedList, PriorityQueue, ….

5 © Peter Andreae COMP 103 04:5 Queue Operations offer(value) ⇒ boolean (sometimes called “enqueue” ) add a value to the queue poll() ⇒ value (sometimes called “dequeue” ) remove and return value at front/head of queue or null if the queue is empty peek() ⇒ value return value at head of queue, or null if queue is empty (doesn’t remove from queue) remove() and element() like poll() and peek(), but throw exception if queue is empty. and all the Collection operations Why use Queue instead of List??

6 © Peter Andreae COMP 103 04:6 A Queue Example. Simulation of a bank with two teller queues: want to see how it will cope with various client loads: how big might the queues get? assume that each client will go to the shortest queue What do we care about? How often a new client turns up. Probability of arriving How long a client will take at the teller Represent client by number of timesteps they will take.

7 © Peter Andreae COMP 103 04:7 A Queue Example. public void simulate(int serveTime, double probArrival){ int t1 = 0; // how many more time steps will the teller be busy int t2 = 0; Queue q1 = new LinkedList (); Queue q2 = new LinkedList (); for (int time =0; time< MaxTime; time++){ if ( Math.random()< probArrival) { int client = (int) (Math.random()*serveTime); if ( q1.size()<q2.size() ) q1.offer(client); else q2.offer(client); } if ( t1==0 && !q1.isEmpty() ) t1 = q1.poll(); if ( t2==0 && !q2.isEmpty() ) t2 = q2.poll(); if (t1 > 0) t1-- ; if (t2 > 0) t2-- ; UI.printf("queues: %d %d /n", q1.size(), q2.size()); }}

8 © Peter Andreae COMP 103 04:8 Collection of data, but not of single values: Map = set of pairs of keys to values Constrained access: get values via keys. No duplicate keys Lots of implementations, most common is HashMap. Maps “Sharon” ⇒ 5978 “David” ⇒ 5656 “Marcus” ⇒ 5672 “Will” ⇒ 5670 “Pondy” ⇒ 5834 get(“Pondy”) put(“Pondy”, 1212) put(“James”, 5134)

9 © Peter Andreae COMP 103 04:9 When declaring and constructing, must specify two types: Type of the key, and type of the value private Map phoneBook; : phoneBook = new HashMap (); Central operations: get(key), → returns value associated with key (or null) put(key, value),→ sets the value associated with key (and returns the old value, if any) remove(key), → removes the key and associated value (and returns the old value, if any) containsKey(key), → boolean size() Maps

10 © Peter Andreae COMP 103 04:10 Example of using Map /** Construct histogram of counts of all temperatures in a file */ public Map countTemps(Scanner sc){ // construct new map // for each temperature in file // if temperture is in the map, increment its count // else, put it in map with a count of 1 // return map } /** Find temperture in histogram with highest count */ public Double findMostFrequentTemp(Map counts){ // for each temperature in map // if has higher count than current most frequent, record it // return most frequent temp } UI.println(findMostFrequentTemp(countTemps(tempFileScanner)));

11 © Peter Andreae COMP 103 04:11 Example of using Map /** Construct histogram of counts of all temperatures in a file */ public Map countTemps(Scanner scan){ Map counts = new HashMap (); while (scan.hasNext()){ double temp = scan.nextDouble(); if ( counts.containsKey(temp) ) counts.put(temp, counts.get(temp)+1); else counts.put(temp, 1); } return counts; } /** Find most frequent temperature */ public Double findMostFrequentTemp(Map counts){ // for each temperature in map // if has higher count than current most frequent, record it // return most frequent temp }

12 © Peter Andreae COMP 103 04:12 Iterating through a Map How do you iterate through a Map? (eg, to print it out) A Map isn’t just a collection of items! ⇒ could iterate through the collection of keys ⇒ could iterate through the collection of values ⇒ could iterate through the collection of pairs Java Map allows all three! keySet()→ Set of all keys for (String name : phonebook.keySet()){…. values()→ Collection of all values for (Integer num : phonebook.values()){…. entrySet()→ Set of all Map.Entry’s for (Map.Entry entry : phonebook.entrySet()){…. … entry.getKey() … … entry.getValue()…

13 © Peter Andreae COMP 103 04:13 Iterating through Map: keySet /** Find most frequent temperature */ public Double findMostFrequentTemp(Map counts){ double mfTemp = Double.NaN; int maxCount = -1; for (Double temp : counts.keySet() ){ int count = counts.get(temp); if (count > maxCount){ maxCount = count; mfTemp = temp; } return mfTemp; }

14 © Peter Andreae COMP 103 04:14 Iterating through Map: entrySet public Double findMostFrequentTemp(Map counts){ double mfTemp = Double.NaN; int maxCount = -1; for (Map.Entry entry : counts.entrySet() ){ if (entry.getValue() > maxCount){ maxCount = entry.getValue(); mfTemp = entry.getKey(); } return mfTemp; } “public” ⇒ 1 “Map” ⇒ 2 “String” ⇒ 5 “counts” ⇒ 2 “findMaxCount” ⇒ 1 Map.Entry - getKey() - getValue()

15 © Peter Andreae COMP 103 04:15 Another example of Map private Map movieCast = new Ha; // character → actor : public void lookup(){ String name = UI.askString(“Character to look up"); if (movieCast.containsKey(name)) UI.println(name +" : "+movieCast.get(name)); else UI.println("No entry for "+ name); } public void update(){ String name = askName(“Character to update"); String actor =askName(“Actor who played "+name); String old = movieCast.put(name, actor); if (old==null) UI.println(" added "+name +" played by " + actor); else UI.println(" replaced "+old+" by "+actor+ " for " + name)); }

16 © Peter Andreae COMP 103 04:16 Sets Set is a collection with: no structure or order maintained no access constraints (access any item any time) Only constraint is that duplicates are excluded Operations: add(value) → true iff collection changed (ie, not duplicate) remove(value) → returns true iff a collection was changed contains(value)→ returns true iff value is in bag uses equal to test. Plus size(), isEmpty(), iterator(), clear(), addAll(collection), removeAll(collection)… Standard implementations: HashSet, TreeSet,

17 © Peter Andreae COMP 103 04:17 Using Sets Checking vocabulary of children’s books: private Set words = new HashSet (); public void readBook(Scanner sc){ while (sc.hasNext ()) words.add(sc.next()); } public void checkWord(String wd){ if (words.contains(wd)) System.out.println(“Yes, ”+wd+“ is in current book”); else System.out.println(“No, ”+wd+“ is not in current book”); } public void printVocab(){ for (String word : words) System.out.println(wd); }


Download ppt "Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington2012 More Collections: Queues,"

Similar presentations


Ads by Google