Lecture 3: Maps and Iterators

Slides:



Advertisements
Similar presentations
Stacks, Queues, and Linked Lists
Advertisements

Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
Abstract Data Types (ADTs) Data Structures The Java Collections API
Implementing Stacks Ellen Walker CPSC 201 Data Structures Hiram College.
Data structures Abstract data types Java classes for Data structures and ADTs.
Java Methods Big-O Analysis of Algorithms Object-Oriented Programming
Collections Mrs. C. Furman April 21, Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet.
List Interface and Linked List Mrs. Furman March 25, 2010.
Week 15 – Wednesday.  What did we talk about last time?  Review up to Exam 1.
Sorting and "Big Oh" ASFA AP Computer Science A SortingBigOh.
CSE373: Data Structures & Algorithms Priority Queues
CSc 110, Autumn 2016 Lecture 26: Sets and Dictionaries
CSE373: Data Structures & Algorithms
Computing with C# and the .NET Framework
CSE 373 Implementing a Stack/Queue as a Linked List
September 29 – Stacks and queues
Searching – Linear and Binary Searches
Wednesday Notecards. Wednesday Notecards Wednesday Notecards.
Chapter 20 Lists, Stacks, Queues, and Priority Queues
CS 1114: Implementing Search
Week 8 - Wednesday CS221.
Teach A level Computing: Algorithms and Data Structures
Data Structures and Algorithms
Lecture 3: Working with Data Structures
CSc 110, Spring 2018 Lecture 32: Sets and Dictionaries
Map interface Empty() - return true if the map is empty; else return false Size() - return the number of elements in the map Find(key) - if there is an.
Top Ten Words that Almost Rhyme with “Peas”
Road Map CS Concepts Data Structures Java Language Java Collections
Lecture 1: Welcome to CSE 373
structures and their relationships." - Linus Torvalds
Lecture 2: Implementing ADTs
Lecture 2: Implementing ADTs
Building Java Programs
Lecture 14: binary search and complexity reading:
CSE 143 Lecture 5 Binary search; complexity reading:
Data Structures and Algorithms
Data Structures and Algorithms
Sets (11.2) set: A collection of unique values (no duplicates allowed) that can perform the following operations efficiently: add, remove, search (contains)
Lecture 3: Queues, Testing, and Working with Code
Data Structures and Algorithms
CSE 143 Lecture 5 More Stacks and Queues; Complexity (Big-Oh)
CSE 373: Data Structures and Algorithms
B-Tree Insertions, Intro to Heaps
CSE 143 Lecture 6 Interfaces; Complexity (Big-Oh)
Data Structures and Algorithms
Lecture 5: Master Theorem, Maps, and Iterators
Lecture 15: binary search reading:
Implementing Hash and AVL
CSE 143 Lecture 8 More Stacks and Queues; Complexity (Big-Oh)
"He's off the map!" - Eternal Sunshine of the Spotless Mind
Exercise Write a program that counts the number of unique words in a large text file (say, Moby Dick or the King James Bible). Store the words in a collection.
Building Java Programs
CSE 373 Java Collection Framework, Part 2: Priority Queue, Map
Building Java Programs
Sets (11.2) set: A collection of unique values (no duplicates allowed) that can perform the following operations efficiently: add, remove, search (contains)
CSE 373: Data Structures and Algorithms
CSE 143 Lecture 8 More Stacks and Queues; Complexity (Big-Oh)
Lecture 2: Stacks and Queues
Lecture 3: Maps and Iterators
slides created by Marty Stepp
Building Java Programs
Sum this up for me Let’s write a method to calculate the sum from 1 to some n public static int sum1(int n) { int sum = 0; for (int i = 1; i
Lecture 4: Introduction to Code Analysis
Lecture 9: Intro to Trees
Lecture 2: Stacks and Queues
CSE 373: Data Structures and Algorithms
CSE 373 Set implementation; intro to hashing
structures and their relationships." - Linus Torvalds
Presentation transcript:

Lecture 3: Maps and Iterators CSE 373: Data Structures and Algorithms CSE 373 19 sp - Kasey Champion

Warm Up Take 3 Minutes Q: Which ADT and data structure implementation would you choose if asked to implement a collection of comments for an Instagram post? List ADT get(index) return item at index set(item, index) replace item at index append(item) add item to end of list insert(item, index) add item at index delete(index) delete item at index size() count of items state behavior Set of ordered items Count of items Stack ADT push(item) add item to top pop() return and remove item at top peek() look at item at top size() count of items isEmpty() count of items is 0? state behavior Set of ordered items Number of items Queue ADT add(item) add item to back remove() remove and return item at front peek() return item at front size() count of items isEmpty() count of items is 0? state behavior Set of ordered items Number of items ArrayList – optimize for addition in order, the ability to remove regardless of position and update number of likes Extra Credit: Go to PollEv.com/champk Text CHAMPK to 22333 to join session, text “1” or “2” to select your answer CSE 373 19 sp - Kasey Champion LinkedList<E> get loop until index, return node’s value set loop until index, update node’s value append create new node, update next of last node insert create new node, loop until index, update next fields delete loop until index, skip node size return size state behavior Node front size LinkedQueue<E> add – add node to back remove – return and remove node at front peek – return node at front size – return size isEmpty – return size == 0 state behavior Node front Node back size ArrayStack<E> push data[size] = value, if out of room grow data pop return data[size - 1], size-1 peek return data[size - 1] size return size isEmpty return size == 0 state behavior data[] size LinkedStack<E> push add new node at top pop return and remove node at top peek return node at top size return size isEmpty return size == 0 state behavior Node top size ArrayList<E> get return data[index] set data[index] = value append data[size] = value, if out of space grow data insert shift values to make hole at index, data[index] = value, if out of space grow data delete shift following values forward size return size state behavior data[] size ArrayQueue<E> add – data[size] = value, if out of room grow data remove – return data[size - 1], size-1 peek – return data[size - 1] size – return size isEmpty – return size == 0 state behavior data[] Size front index back index

Administrivia CSE 373 19 wi - Kasey Champion

Review: Complexity Class complexity class: A category of algorithm efficiency based on the algorithm's relationship to the input size N. Complexity Class Big-O Runtime if you double N Example Algorithm constant O(1) unchanged Accessing an index of an array logarithmic O(log2 N) increases slightly Binary search linear O(N) doubles Looping over an array log-linear O(N log2 N) slightly more than doubles Merge sort algorithm quadratic O(N2) quadruples Nested loops! ... exponential O(2N) multiplies drastically Fibonacci with recursion CSE 373 19 wi - Kasey Champion

Review: Maps key value “at" 43 key value “in" 37 key value “you" 22 map: Holds a set of unique keys and a collection of values, where each key is associated with one value. a.k.a. "dictionary", "associative array", "hash" key value “the" 56 map.get("the") 56 supported operations: put(key, value): Adds a given item into collection with associated key, if the map previously had a mapping for the given key, old value is replaced get(key): Retrieves the value mapped to the key containsKey(key): returns true if key is already associated with value in map, false otherwise remove(key): Removes the given key and its mapped value Dictionary ADT put(key, item) add item to collection indexed with key get(key) return item associated with key containsKey(key) return if key already in use remove(key) remove item and associated key size() return count of items state behavior Set of items & keys Count of items CSE 143 SP 17 – zora fung

Implementing a Dictionary with an Array 2 Minutes Implementing a Dictionary with an Array Dictionary ADT put(key, item) add item to collection indexed with key get(key) return item associated with key containsKey(key) return if key already in use remove(key) remove item and associated key size() return count of items state behavior Set of items & keys Count of items ArrayDictionary<K, V> put create new pair, add to next available spot, grow array if necessary get scan all pairs looking for given key, return associated item if found containsKey scan all pairs, return if key is found remove scan all pairs, replace pair to be removed with last pair in collection size return count of items in dictionary state behavior Pair<K, V>[] data Big O Analysis put() get() containsKey() remove() size() O(n) linear O(n) linear O(n) linear O(n) linear O(1) constant put(‘a’, 1) put(‘b’, 2) put(‘c’, 3) put(‘d’, 4) remove(‘b’) put(‘a’, 97) 1 2 3 (‘a’, 1) 97) (‘b’, 2) (‘c’, 3) (‘d’, 4) CSE 373 19 wi - Kasey Champion

Implementing a Dictionary with Nodes 2 Minutes Implementing a Dictionary with Nodes Dictionary ADT put(key, item) add item to collection indexed with key get(key) return item associated with key containsKey(key) return if key already in use remove(key) remove item and associated key size() return count of items state behavior Set of items & keys Count of items LinkedDictionary<K, V> put if key is unused, create new with pair, add to front of list, else replace with new value get scan all pairs looking for given key, return associated item if found containsKey scan all pairs, return if key is found remove scan all pairs, skip pair to be removed size return count of items in dictionary state behavior front size Big O Analysis put() get() containsKey() remove() size() O(n) linear O(n) linear O(n) linear O(n) linear O(1) constant put(‘a’, 1) put(‘b’, 2) put(‘c’, 3) put(‘d’, 4) remove(‘b’) put(‘a’, 97) front ‘d’ 4 ‘c’ 3 ‘b’ 2 ‘a’ 97 1 CSE 373 19 sp - Kasey Champion

Design Decisions Take 5 Minutes Discuss with your neighbors: Which implementation of the Dictionary ADT would you choose if asked to implement each of the following situations? For each consider the most important functions to optimize. Situation #1: You are writing a program to store incidents in a software service you maintain. The keys will be time stamps, so you know they will be unique. You will be adding incidents as they occur and removing them as they are resolved. You are more likely to need to access and remove incidents that have recently been added to the collection. LinkedDictionary – optimize for addition and removal of incidents without need of examining entire data set reguarly Situation #2: You are writing a program to store a rather small dictionary that maps exam questions to the average score for that question across all students. The questions are numbered sequentially starting at 0. Often you will want to read the entire set of scores in the order of the test. ArrayDictionary – optimize for accessing all entries in set in specific order or individually CSE 373 19 sp - Kasey Champion

Traversing Data Iterator! Array List for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } List for (int i = 0; i < myList.size(); i++) { System.out.println(myList.get(i)); for (T item : list) { System.out.println(item); Iterator! CSE 373 SP 18 - Kasey Champion

Review: Iterators iterator: a Java interface that dictates how a collection of data should be traversed. Can only move in the forward direction and in a single pass. Iterator Interface hasNext() – true if elements remain next() – returns next element behavior supported operations: hasNext() – returns true if the iteration has more elements yet to be examined next() – returns the next element in the iteration and moves the iterator forward to next item ArrayList<Integer> list = new ArrayList<Integer>(); //fill up list Iterator itr = list.iterator(); while (itr.hasNext()) { int item = itr.next(); } ArrayList<Integer> list = new ArrayList<Integer>(); //fill up list for (int i : list) { int item = i; } CSE 373 19 wi - Kasey Champion

Implementing an Iterator hasNext() itr front 4 3 2 1 true itr false front 4 3 2 1 next() Implement over the map we just made itr 4 front 4 3 2 1 itr front 4 3 2 1 2 CSE 373 19 wi - Kasey Champion

Testing Your Code CSE 373 19 wi - Kasey Champion

Testing Computers don’t make mistakes- people do! “I’m almost done, I just need to make sure it works” – Naive 14Xers Software Test: a separate piece of code that exercises the code you are assessing by providing input to your code and finishes with an assertion of what the result should be. Isolate - break your code into small modules Build in increments - Make a plan from simplest to most complex cases Test as you go - As your code grows, so should your tests CSE 373 SP 18 - Kasey Champion

Types of Tests Black Box White Box Behavior only – ADT requirements From an outside point of view Does your code uphold its contracts with its users? Performance/efficiency White Box Includes an understanding of the implementation Written by the author as they develop their code Break apart requirements into smaller steps “unit tests” break implementation into single assertions CSE 373 SP 18 - Kasey Champion

What to test? Expected behavior Forbidden Input Empty/Null The main use case scenario Does your code do what it should given friendly conditions? Forbidden Input What are all the ways the user can mess up? Empty/Null Protect yourself! How do things get started? 0, -1, null, empty collections Boundary/Edge Cases First items Last item Full collections Scale Is there a difference between 10, 100, 1000, 10000 items? CSE 373 SP 18 - Kasey Champion

Testing Strategies You can’t test everything Break inputs into categories What are the most important pieces of code? Test behavior in combination Call multiple methods one after the other Call the same method multiple times Trust no one! How can the user mess up? If you messed up, someone else might Test the complex logic CSE 373 19 wi - Kasey Champion

Thought Experiment 5 Minutes Discuss with your neighbors: Imagine you are writing an implementation of the List interface that stores integers in an Array. What are some ways you can assess your program’s correctness in the following cases: Expected Behavior Create a new list Add some amount of items to it Remove a couple of them Forbidden Input Add a negative number Add duplicates Add extra large numbers Empty/Null Call remove on an empty list Add to a null list Call size on an null list Boundary/Edge Cases Add 1 item to an empty list Set an item at the front of the list Set an item at the back of the list Scale Add 1000 items to the list Remove 100 items in a row Set the value of the same item 50 times CSE 373 SP 18 - Kasey Champion

JUnit JUnit: a testing framework that works with IDEs to give you a special GUI experience when testing your code @Test public void myTest() { Map<String, Integer> basicMap = new LinkedListDict<String, Integer>(); basicMap.put(“Kasey”, 42); assertEquals(42, basicMap.get(“Kasey”)); } Assertions: assertEquals(item1, item2) assertTrue(Boolean expression) assertFalse(bollean expression) assertNotNull(item) More: https://junit.org/junit5/docs/5.0.1/api/org/junit/jupiter/api/Assertions.html CSE 373 SP 18 - Kasey Champion