COMP 103 Maps, Stacks Thomas Kuehne 2016-T2 Lecture 5

Slides:



Advertisements
Similar presentations
Introduction to Stacks What is a Stack Stack implementation using array. Stack implementation using linked list. Applications of Stack.
Advertisements

1 Introduction to Stacks What is a Stack? Stack implementation using array. Stack implementation using linked list. Applications of Stacks.
TCSS 342, Winter 2005 Lecture Notes
Chapter 6 Stacks. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. 6-2 Chapter Objectives Examine stack processing Define a stack abstract.
COMP T2 Lecture 5 School of Engineering and Computer Science, Victoria University of Wellington Thomas Kuehne Maps, Stacks  Thomas Kuehne, Marcus.
Topic 3 The Stack ADT.
Implementing Stacks Ellen Walker CPSC 201 Data Structures Hiram College.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
Data Structures. The Stack: Definition A stack is an ordered collection of items into which new items may be inserted and from which items may be deleted.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Marcus Frean.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington2012 More Collections: Queues,
Some Other Collections: Bags, Sets, Queues and Maps COMP T2 Lecture 4 School of Engineering and Computer Science, Victoria University of Wellington.
2014-T2 Lecture 19 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Lindsay Groves, Peter Andreae, and John.
2013-T2 Lecture 18 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Lindsay Groves, Peter Andreae, and John.
Basic Data Structures Stacks. A collection of objects Objects can be inserted into or removed from the collection at one end (top) First-in-last-out.
Interfaces, Classes, Collections School of Engineering and Computer Science, Victoria University of Wellington COMP T2 Lecture 3 Thomas Kuehne.
Computer Science 209 Software Development Inheritance and Composition.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Thomas Kuehne.
Lecture Objectives  To understand how Java implements a stack  To learn how to implement a stack using an underlying array or linked list  Implement.
Iterators, Iterator, and Iterable 2015-T2 Lecture 8 School of Engineering and Computer Science, Victoria University of Wellington COMP 103 Thomas Kuehne.
Some Other Collections: Bags, Sets, Queues and Maps COMP T2 Lecture 4 School of Engineering and Computer Science, Victoria University of Wellington.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Marcus Frean.
2015-T2 Lecture 19 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Lindsay Groves, Peter Andreae, and John.
COMP 103 Maps and Queues. RECAP  Iterators (for-each loop)  Bag, Sets, and Stacks - a class, not interface TODAY  Maps and Queues 2 RECAP-TODAY QUICK.
CC 215 DATA STRUCTURES MORE ABOUT STACK APPLICATIONS Dr. Manal Helal - Fall 2014 Lecture 6 AASTMT Engineering and Technology College 1.
1 Stacks Abstract Data Types (ADTs) Stacks Application to the analysis of a time series Java implementation of a stack Interfaces and exceptions.
Chapter 3 Lists, Stacks, Queues. Abstract Data Types A set of items – Just items, not data types, nothing related to programming code A set of operations.
Stacks and Queues. 2 Abstract Data Types (ADTs) abstract data type (ADT): A specification of a collection of data and the operations that can be performed.
Prefix notation in action
Stacks Access is allowed only at one point of the structure, normally termed the top of the stack access to the most recently added item only Operations.
Building Java Programs
Stacks II David Lillis School of Computer Science and Informatics
Collections COMP 103 #3 2008T2.
COMP 103 Comperator and Comparable Thomas Kuehne 2015-T2 Lecture 9
Some Collections: BAGS, SETS, and STACKS
Stacks and Queues.
Revised based on textbook author’s notes.
Recap: Solution of Last Lecture Activity
JAVA COLLECTIONS LIBRARY
JAVA COLLECTIONS LIBRARY
The Stack ADT. 3-2 Objectives Define a stack collection Use a stack to solve a problem Examine an array implementation of a stack.
Cinda Heeren / Geoffrey Tien
Implementing ArrayList Part 1
CSE 373: Data Structures and Algorithms
COMP 103 SORTING Lindsay Groves 2016-T2 Lecture 26
Stacks and Queues.
Building Java Programs Chapter 14
Stack Data Structure, Reverse Polish Notation, Homework 7
Road Map CS Concepts Data Structures Java Language Java Collections
Stacks and Queues.
Building Java Programs
Stacks Chapter 5 Adapted from Pearson Education, Inc.
Stacks and Queues.
Lecture 5 Stacks King Fahd University of Petroleum & Minerals
Building Java Programs
Building Java Programs
Stacks and Queues CLRS, Section 10.1.
"He's off the map!" - Eternal Sunshine of the Spotless Mind
Stacks Abstract Data Types (ADTs) Stacks
Cs212: Data Structures Computer Science Department Lecture 6: Stacks.
Stacks.
Topic 15 Implementing and Using Stacks
Jordi Cortadella and Jordi Petit Department of Computer Science
Stacks Chapter 5.
Introduction to Stacks
Introduction to Stacks
Generics, Stack, Queue Based on slides by Alyssa Harding
Stacks and Queues.
CHAPTER 3: Collections—Stacks
Presentation transcript:

COMP 103 Maps, Stacks Thomas Kuehne 2016-T2 Lecture 5 Thomas Kuehne, Marcus Frean, Thomas Kuehne School of Engineering and Computer Science, Victoria University of Wellington 2016-T2 Lecture 5

RECAP-TODAY RECAP So far we’ve looked at these types of Collection 2 RECAP So far we’ve looked at these types of Collection Bag, List, Set, Queue and Map TODAY More on Map Stack (the last of the Collection types we will look at) Collections of collections of...

Maps When declaring and constructing, we must specify two types: 3 When declaring and constructing, we must specify two types: Type of the key, and type of the value private Map<String, PhoneNumber> phoneBook; : phoneBook = new HashMap<String, PhoneNumber> (); 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()

Iterating through a Map 4 How do you iterate through a Map? (e.g., to print it out) A Map isn’t just a collection of single items! ⇒ could iterate through the collection of keys ⇒ could iterate through the collection of values ⇒ could iterate through the collection of keyvalue pairs Java Collection library’s Map allows all of the above! keySet() → Set of all keys for (String name : phonebook.keySet()) {…. values() → Collection of all values for (PhoneNumber num : phonebook.values()) {…. entrySet() → Set of all Map.Entry’s for (Map.Entry<String, Integer> entry : phonebook.entrySet()) { … entry.getKey() … … entry.getValue()… Why Collection of values, not Set of values like the other two? Type for keyvalue pair

Example of using Map Find the highest frequency word in a file 5 Find the highest frequency word in a file ⇒ must count frequency of every word i.e., need to associate a count (int) with each word (String) ⇒ use a Map of “wordcount” pairs Two Steps: construct the counts of each word: countWords(file) → map find the highest count: maxCountWord(map) → word UI.println( maxCountWord( countWords(file) ) );

Design the step-by-step solution (algorithm) before you code Example of using Map 6 // Construct histogram of counts of all words in a file public Map<String, Integer> countWords(Scanner sc) { // construct new map // for each word in file // if word is in the map, increment its count // else, put it in map with a count of 1 // return map } // Find word in histogram with highest count public String maxCountWord(Map<String, Integer> counts) { // for each word in map // if word has higher count than current maximum count then // record it // return last recorded maximum count word “pseudocode” Design the step-by-step solution (algorithm) before you code

Example of using Map 7 // Construct histogram of counts of all words in a file public Map<String, Integer> countWords(Scanner scan){ Map<String, Integer> counts = new HashMap<String, Integer> (); while (scan.hasNext()) { String word = scan.next(); if ( counts.containsKey(word) ) counts.put(word, counts.get(word)+1); else counts.put(word, 1); } return counts;

Example of using Map (faster) 8 // Construct histogram of counts of all words in a file public Map<String, Integer> countWords(Scanner scan){ Map<String, Integer> counts = new HashMap<String, Integer> (); while (scan.hasNext()) { String word = scan.next(); Integer frequency = counts.get(word); counts.put(word, frequency == null ? 1 : frequency + 1); } return counts;

Iterating through Map: entrySet 9 public String maxCountWord(Map<String, Integer> counts) { String maxWord = null; int maxCount = -1; for (Map.Entry<String, Integer> entry : counts.entrySet() ) { if (entry.getValue() > maxCount) { maxCount = entry.getValue(); maxWord = entry.getKey(); } return maxWord; Map.Entry<K,V> - getKey() - getValue() Map.Entry<K,V> - getKey() - getValue() “public” ⇒ 1 “Alice” ⇒ 1 “eavesdrops” ⇒ 5 “private” ⇒ 1 “Bob” ⇒ 2

Stacks Based on the “first in, last out” principle (cf. Queues…) 10 Based on the “first in, last out” principle (cf. Queues…) A special kind of List: Constrained access: add, get, and remove only from one end We should have a Stack interface, and different implementations of it (ArrayStack, LinkedStack, etc.), but... In Java’s Collections library, it is a class that implements List (actually, it extends Vector) So you make one like this: Stack<Integer> myNums = new Stack<Integer> ();

Stacks Stacks have extra operations: push(value), pop(), peek() 11 Stacks have extra operations: push(value), pop(), peek() push(value): Put value on top of stack pop(): Removes and returns top of stack peek(): Returns top of stack, without removing plus the other List operations… (oops!)

Stack example Reversing the items from a file: 12 Reversing the items from a file: read and push onto a stack pop them off the stack public void reverseNums(Scanner sc) { Stack<Integer> myNums = new Stack<Integer> (); while (sc.hasNextInt()) myNums.push(sc.nextInt()) while (! myNums.isEmpty()) UI.print(myNums.pop() + “\n”); }

Applications of Stacks 13 Programs that deal with programs e.g., program execution, e.g., expression evaluation, (6 + 4) * ((10 * √64) – (√81/ 3)) Working on subtasks, returning to previous task Processing files of structured (nested) data e.g., reading files of with structured markup (HTML, XML,…) Undo in editors, or games

Stack for evaluating expressions 14 (6 + 4) * ((10 * √64) – (√81/ 3)) ⇒ ( (6, 4)+ , ((10, (64)√) * , ((81)√, 3)/ )- )* ⇒ 6 4 + 10 64 √ * 81 √ 3 / - * Algorithm if operand → push on stack if operator → pop arguments from stack compute value push on stack if done → pop answer from stack Postfix order (also known as “Reverse Polish Notation”)

Summary of these recent collection types 15 Queue First in, first out (FIFO) Always remove from one end Ordinary queue: add at the opposed end Priority queue: add anywhere, according to priority Stack First in, last out (FILO) [Java: No Stack interface, just a class, named “Stack”, with lax control] Map KeyValue pairs Three ways to iterate: over set of Keys, over collection of Values, over set of KeyValue pairs KeyValue pairs represented using Map.Entry<K,V> Efficiency: you can make queues that are very efficient for the constrained access actions, but would not be efficient for general list operations. Clarity: By declaring it as a queue, you make it clear to other programmers reading/modifying your code what this collection is for and how it should be used. Error prevention: The compiler will stop you from doing illegal operations on a Queue, whereas, if it were a list, you might write them by mistake. Note: if you need to be able to access the middle of the queue, and mess with it, then you will need to use a list. 15

Collections of collections? 16 Yes! A collection is an object. Often really useful, for instance, a List of Sets a Map, from Strings into Lists (of...) Examples: A list of sets of ingredients Map of Maps: name -> (workPhone -> #, homePhone -> #)