Plan for Week l Linear structures Stack Queue

  • Slides: 25
Download presentation
Plan for Week l Linear structures: Stack, Queue Ø Applications: LIFO, FIFO, other Ø

Plan for Week l Linear structures: Stack, Queue Ø Applications: LIFO, FIFO, other Ø Canonical examples and view to more Ø Java specifics of how to use these l Friday: More examples of recursion and alternatives Ø Blob counting and applications of neighborsearch l Guide to using practice-it for APT-like problems Compsci 201, Fall 2016 14. 1

What is a linear structure? l l Structure elements have predecessors, successors Arrays, Linked-lists,

What is a linear structure? l l Structure elements have predecessors, successors Arrays, Linked-lists, Array. Lists Ø ADT: insert, delete, iterate/traverse, grow, … Ø Advantages and trade-offs include … Some linear structures are used to solve problems and are typically studied in courses like 201 Ø We won't look in detail at implementations Ø We will mention the implementations Ø 201, Viewed via APIs and problems solved 14. 2 Compsci Fall 2016 l

Stacks Queues and Deques, Oh My! l Linear structures used in problem domains and

Stacks Queues and Deques, Oh My! l Linear structures used in problem domains and algorithms: Stack, Queue, Dequeue. Ø Similar abstractions with different semantics Compsci 201, Fall 2016 14. 3

https: //www. google. com/search? q=stack&source=lnms&tbm=isch Compsci 201, Fall 2016 14. 4

https: //www. google. com/search? q=stack&source=lnms&tbm=isch Compsci 201, Fall 2016 14. 4

https: //www. google. com/search? q=queue&source=lnms&tbm=isch Compsci 201, Fall 2016 14. 5

https: //www. google. com/search? q=queue&source=lnms&tbm=isch Compsci 201, Fall 2016 14. 5

Why don't we just use arrays? l Stacks used in implementing recursion, postscript language,

Why don't we just use arrays? l Stacks used in implementing recursion, postscript language, Java language, graph algorithms Ø Stacks implemented using array/Array. List l Queues used in simulation, graph algorithms, scheduling Ø Queues implemented using array/Linked. List Deque (dequeue) double ended queue, Gradescope Ø Implemented using Linked. List or other Compsci 201, Fall 2016 l 14. 6

Stacks: Java and Otherwise https: //git. cs. duke. edu/201 fall 16/linearstructures/tree/master/src l l l

Stacks: Java and Otherwise https: //git. cs. duke. edu/201 fall 16/linearstructures/tree/master/src l l l See Stack. Demo. java Ø Note that Stack is in java. util Ø Stack is generic, e. g. , Stack<String> https: //docs. oracle. com/javase/8/docs/api/java/util /Stack. html Ø See API documentation for details on methods In code example: push, pop, create, size Ø Also noted is. Empty and peek Compsci 201, Fall 2016 14. 7

Simple stack example l Stack is part of java. util. Collections hierarchy Ø Typically

Simple stack example l Stack is part of java. util. Collections hierarchy Ø Typically avoid. peek(), but can be useful Stack<String> s = new Stack<>(); s. push("panda"); s. push("grizzly"); s. push("brown"); System. out. println("size = "+s. size()); System. out. println(s. peek()); String str = s. pop(); System. out. println(s. peek()); System. out. println(s. pop()); Compsci 201, Fall 2016 14. 8

Two applications of stacks l l l Manage runtime of method invocations, e. g.

Two applications of stacks l l l Manage runtime of method invocations, e. g. , in implementing compiler. Note that Java Virtual machine is a stack-based machine Postfix notation for arithmetic expressions Ø Can be used in evaluating expressions Ø What is 3 + 5 * 7 ? This is NOT 56 Ø Without precedence, need parentheses, e. g. , we'd write (3 + 5) * 7 Postfix is sometimes called Reverse Polish Notation or RPN Ø https: //en. wikipedia. org/wiki/Reverse_Polish_notation Compsci 201, Fall 2016 14. 9

Postfix, prefix, and infix notation l Postfix notation used in some HP calculators Ø

Postfix, prefix, and infix notation l Postfix notation used in some HP calculators Ø No parentheses needed, precedence rules work 3 5 + 4 2 * 7 + 3 9 7 + * Ø Read expression • For number/operand: push onto stack • For operator: pop, operate, push l To evaluate prefix: (3 + 5) * 7 we'd use Ø 35+7* Ø What is 3 5 7 * + Compsci 201, Fall 2016 14. 10

Postfix. java l To evaluate a postfix expression: Ø If number, push. If operator:

Postfix. java l To evaluate a postfix expression: Ø If number, push. If operator: pop, op, push l https: //git. cs. duke. edu/201 fall 16/linearstructures/blob/maste r/src/Postfix. java l Things to look at in program: What exceptions are caught? When do these occur? Ø Number format and Stack exceptions How does String. Tokenizer work: Ø Like. split(), but delivers tokens or chunks one at a time. Delimiters or separators are tokens too l Compsci 201, Fall 2016 14. 11

Modifying Postfix. java l How can we add exponentiation to the program Ø 2

Modifying Postfix. java l How can we add exponentiation to the program Ø 2 3 ^ would be 8 and 3 2 ^ would be 9 l Must add new delimiter Ø What happens before we add ^ when ^ entered? Ø What happens after we add ^ when ^ entered? l Must add new line in method operator Ø How do we return appropriate value? Test? Compsci 201, Fall 2016 14. 12

WOTO http: //bit. ly/201 fall 16 -stacks l Look at source code for Postfix.

WOTO http: //bit. ly/201 fall 16 -stacks l Look at source code for Postfix. java to understand both RPN and parsing using tokens in Java Compsci 201, Fall 2016 14. 13

Barbara Liskov Turing Award Winner in 2008 for For contributions to practical and theoretical

Barbara Liskov Turing Award Winner in 2008 for For contributions to practical and theoretical foundations of programming language and system design, especially related to data abstraction, fault tolerance, and distributed computing. The advice I give people in general is that you should figure out what you like to do, and what you can do well—and the two are not all that dissimilar, because you don’t typically like doing something if you don’t do it well. … So you should instead watch—be aware of what you’re doing, and what the opportunities are, and step into what seems right, and see where it takes you. Compsci 201, Fall 2016 14. 14

Queue: another linear ADT l l FIFO: first in, first out, used in many

Queue: another linear ADT l l FIFO: first in, first out, used in many applications Ø Scheduling jobs/processes on a computer Ø Computer simulations, lines at stores or banks: one line or multiple lines? Common operations: add (back), remove (front), peek ? ? Ø java. util. Queue is an interface Ø java. util. Linked. List implements the interface • add(), remove(), offer(), poll() Compsci 201, Fall 2016 14. 15

Stacks: Java and Otherwise https: //git. cs. duke. edu/201 fall 16/linearstructures/tree/master/src l l l

Stacks: Java and Otherwise https: //git. cs. duke. edu/201 fall 16/linearstructures/tree/master/src l l l See Queue. Demo. java Ø Note that Queue is in java. util and is an Interface! Typically use Linked. List to create concrete object https: //docs. oracle. com/javase/8/docs/api/java/util /Queue. html Ø See API documentation for details on methods and on many implementing classes Why use Linked. List? O(1) add back, remove front Compsci 201, Fall 2016 14. 16

Simple Queue example l Queueis part of java. util. Collections hierarchy Ø Typically avoid.

Simple Queue example l Queueis part of java. util. Collections hierarchy Ø Typically avoid. peek(), but can be useful Queue<String> q = new Linked. List<>(); q. add("panda"); q. add("grizzly"); q. add("brown"); System. out. println("size = "+q. size()); System. out. println(q. peek()); String str = q. remove(); System. out. println(q. peek()); System. out. println(q. remove()); Compsci 201, Fall 2016 14. 17

Queue applications l Simulation, discrete-event simulation Ø How many toll-booths do we need? How

Queue applications l Simulation, discrete-event simulation Ø How many toll-booths do we need? How many express lanes or self-checkout at grocery store? Runway access at airport? Ø Queues facilitate simulation with mathematical distributions governing events, e. g. , Poisson distribution for arrival times l Shortest path, e. g. , in word-ladder or Flood-Fill algorithms we'll see on Friday Ø Get from "white" to "house" one-letter at a time? Compsci 201, Fall 2016 • white, while, whale, shake, …? 14. 18

Wordladder Story l l Ladder from ‘white’ to ‘house’ Ø White, while, whale, shale,

Wordladder Story l l Ladder from ‘white’ to ‘house’ Ø White, while, whale, shale, … I can do that… optimally Ø My brother was an English major Ø My ladder is 16, his is 15, how? There's a ladder that's 14 words! Ø The key is ‘sough’ Guarantee optimality! Ø QUEUE Compsci 201, Fall 2016 14. 19

Queue for shortest path – see gitlab public boolean find. Ladder(String[] words, String first,

Queue for shortest path – see gitlab public boolean find. Ladder(String[] words, String first, String last){ Queue<String> qu = new Linked. List<>(); Set<String> set = new Hash. Set<>(); qu. add(first); while (qu. size() > 0){ String current = qu. remove(); if (one. Away(current, last)) return true; for(String s : words){ if (! set. contains(s) && one. Away(from, s)){ qu. add(s); set. (s); } } return false; Compsci 201, Fall 2016 14. 20

Shortest Path reprised l How does Queue ensure we find shortest path? Ø Where

Shortest Path reprised l How does Queue ensure we find shortest path? Ø Where are words one away from first? Ø Where are words two away from first? l Why do we need to avoid revisiting a word, when? Ø Why do we use a set for this? Why a Hash. Set? Ø Alternatives? If we want the ladder, not just whether it exists Ø What's path from white to house? We know there is one. l Compsci 201, Fall 2016 14. 21

Shortest path proof l l l All words one away from start on queue

Shortest path proof l l l All words one away from start on queue first iteration Ø What is first value of current when loop entered? All one-away words dequeued before two-away Ø See previous assertion, property of queues Ø Two-away before 3 -away, … Each 2 -away word is one away from a 1 -away word Ø So all enqueued after one-away, before threeaway • How do we find three-away word? l Compsci Any 201, w. Fall seen/dequeued 2016 Ø that's n-away is: Seen before every n+k-away word for k >=1! 14. 22

Keeping track of ladder l Find w, a one-away word from current Ø Enqueue

Keeping track of ladder l Find w, a one-away word from current Ø Enqueue w if not seen Ø Call map. put(w, current) l Remember keys are unique! Ø Put word on queue once! Ø map. put("lot", "hot") Ø map. put("dot", "hot") Ø map. put("hat", "hot") Compsci 201, Fall 2016 14. 23

Reconstructing Word Ladder l Run Word. Ladders. Full Ø https: //git. cs. duke. edu/201

Reconstructing Word Ladder l Run Word. Ladders. Full Ø https: //git. cs. duke. edu/201 fall 16/linearstructure s/blob/master/src/Word. Ladders. Full. java l Notice map and call to map. put(word, current) Ø Ø What about when returning the ladder, why is the returned ladder in reverse order? What do we know about code when statement adding (key, value) to map runs? Compsci 201, Fall 2016 14. 24

WOTO http: //bit. ly/201 fall 16 -queue What's your favorite word ladder? Could you

WOTO http: //bit. ly/201 fall 16 -queue What's your favorite word ladder? Could you write code to find the longest word ladder? Compsci 201, Fall 2016 14. 25