Download presentation
Presentation is loading. Please wait.
1
Chapter 6 – Queues and Deques
Lab 06 – Railroad 7.1 Recursive Thinking Chapter 6 – Queues and Deques
2
Tip #22: Keep Fit To Program Better
Queues / Deques It may seem obvious, but it is 100% true: int main(void) { Exercise you("Your name here"); you.do_pushups(25); you.do_situps(30); you.lift_weights(100); if (you.tired()) you.rest_for_a_while(); you.get_back_to_work(); } return 0; If a programmer exercises regularly, he/she can program better. You don't have to worry about physical problems like stiffness or boredom. Exercising make's you feel better about yourself.
3
Lab 06 – Railroad
4
Lab 06 - Railroad Recursion Create a railroad train station that uses a central turntable and roundhouses to store train cars as well as changes the order of cars entering and leaving the station. Cars may enter the train station if the turntable is empty. From the turntable cars can be moved to a "stack" roundhouse facility (LIFO) or a "queue" roundhouse facility (FIFO). Train cars leave the train station by moving from the turntable to a "vector" of outbound cars. What Objects? How to describe them? UML
5
DequeInterface<T>
Vector<T> -container__:Deque<T> +Vector() +~Vector() +push_back(const T&):void +pop_back():void +back():T& +size():size_t +at(size_t):T& +toString() const:string <<interface>> DequeInterface<T> +static const size_t DEFAULT_CAPACITY = 4 +DequeInterface() +~DequeInterface() +push_front(const T&):void +push_back(const T&):void +pop_front():void +pop_back():void +front():T& +back():T& +size():size_t +empty() const:bool +at(size_t):T& +toString() const:string Station<T> -train_:Vector<T> -stack_:Stack<T> -queue_:Queue<T> -turnTableCar_:T -empty:bool +Station() +~Station() +addCar(const T&):string +removeCar():string +topCar():string +addStack():string +removeStack():string +topStack():string +sizeStack():string +addQueue():string +removeQueue():string +topQueue():string +sizeQueue():string +find(T):string +toString() const:string Deque<T> -capacity:size_t -num_items:size_t -front_index:size_t -rear_index:size_t -the_data:T* +Deque() +~Deque() +push_front(const T&):void +push_back(const T&):void +pop_front():void +pop_back():void +front():T& +back():T& +size():size_t +empty() const:bool +at(size_t):T& +toString() const:string -reallocate():void Queue<T> -container__:Deque<T> +Queue() +~Queue() +push(const T&):void +pop():void +top():T& +size():size_t +at(size_t):T& +toString() const:string Stack<T> -container__:Deque<T> +Stack() +~Stack() +push(const T&):void +pop():void +top():T& +size():size_t +at(size_t):T& +toString() const:string
6
Circular Buffer capacity = 16 num_items = 5 the_data L O H E
Recursion capacity = 16 num_items = 5 the_data L O H E rear_index front_index /** Return a reference to an item in the deque. */ T& operator[](size_t index) { return the_data[(index + front_index) % capacity]; } front_index the_data rear_index
7
Specification of the Deque
Recursion Behavior Member Function Insert element at back void push_back(item) Insert element at front void push_front(item) Remove last element void pop_back(); Remove first element void pop_front(); Examine last element item& back(); Examine first element item& front(); Index item& at(index); Size size_t size(); *Insert element iterator insert(iterator, item); *Remove all items void remove(item); *Index item& [] *Iterator start iterator begin(); *Iterator end iterator end(); *Not Required for Lab 06 Deque
8
Wrapper Class Recursion A wrapper class is a class that encapsulates or contains another class and uses its functionality to define the class' behavior. #include "Deque.h" template <typename T> class Stack { private: Deque<T> deque_; public: void push(T data) deque_.push_back(data); } void pop(void) deque_.pop_back(); ... }; #include "Deque.h" template <typename T> class Queue { private: Deque<T> deque_; public: void push(T data) deque_.push_back(data); } void pop(void) deque_.pop_front(); ... };
9
L06 – Railroad Wrapper Classes
Recursion Input Commands Station 235 Station<T> string addCar(const T&); string addStack(); string addQueue(); string removeCar(); string removeStack(); string removeQueue(); string topCar(); string topStack(); string topQueue(); string sizeStack(); string sizeQueue(); string find(T); string toString() const; "Add:station xx" "Add:stack" "Add:queue" "Remove:station" "Remove:stack" "Remove:queue" "Top:station" "Top:stack" "Top:queue" "Size:stack" "Size:queue" "Find:xx" "Train:" Vector<T>, Queue<T>, Stack<T> void push(const T&); void pop(); void top(); size_t size(); T& at(size_t); string toString() const; Deque<T> void push_front(const T&); void push_back(const T&); void pop_front(); void pop_back(); T& front(); T& back(); size_t size(); bool empty() const; T& at(size_t); string toString() const; <<interface>> DequeInterface<T> typedef unsigned int size_t;
10
Station Commands Recursion COMMAND DESCRIPTION OUTPUT
Add:station <data> Add:queue <data> Add:stack <data> Train car enters the station turntable. Train car is removed from the turntable and pushed to the Queue roundhouse. Train car is removed from the turntable and pushed to the Stack roundhouse. OK Turntable occupied! Turntable empty! Remove:station Remove:queue Remove:stack A train car is removed from the turntable and pushed into the train vector. A train car is removed from Queue roundhouse and moved to the station turntable. A train car is removed from Stack roundhouse and moved to the station turntable. OK Turntable empty! Turntable occupied! Queue empty! Stack empty! Top:station Top:queue Top:stack Display the current train car on station turntable, Display the train car at head of Queue roundhouse. Display the train car at head of Stack roundhouse. <data> Turntable empty! Queue empty! Stack empty! Size:queue Size:stack Output number of train cars in Queue/Stack roundhouse. Size of Queue/Stack Find: <data> Find and display the current location and position of a car in the station data structures (turntable, queue, stack, or vector). Turntable Queue[<index>] Stack[<index>] Train[<index>] Not Found! Train: Output the contents of the train vector. List of train cars leaving the station.
11
Requirements 10 2 -10 L06 - Railroad Points
Requirement ( Points) 10 As train cars exit the station turntable, they are pushed on a train Vector template class that has-a Deque container and operates as described above (lab06_in_01.txt). The Stack roundhouse consists of a LIFO template class that has-a Deque container and operates as described above (lab06_in_02.txt). The Queue roundhouse consists of a FIFO template class that has-a Deque container and operates as described above (lab06_in_03.txt). All the station containers (Queue, Stack, Vector) resize correctly (lab06_in_04.txt). BONUS: The Find command finds a train car in the station data structures (queue or stack) or the train vector. If found, the name of the structure and the index within the structure is displayed (as described above.) (lab06_in_05.txt). -10 Memory leaks, g++ compiler warnings, array out-of-bounds, or use of STL container detected. Points Peer Review 2 A Deque template class is implemented using a dynamic circular array and is derived from the abstract DequeInterface interface class. All station facility containers (stack, queue, vector, deque) are separate classes that are implemented by "wrapping" your Deque template class.
12
Chapter 7 Recursion
13
Objectives To understand how to think recursively.
Recursion To understand how to think recursively. To learn how to trace a recursive function. To learn how to write recursive algorithms and functions for searching vectors. To understand how to use recursion to solve the Towers of Hanoi problem. To understand how to use recursion to process two- dimensional images. To learn how to apply backtracking to solve search problems such as finding a path through a maze.
14
Outcomes Recursion Recursion can solve many programming problems that are difficult to conceptualize and solve linearly. In the field of artificial intelligence, recursion often is used to write programs that exhibit intelligent behavior: playing games of chess. proving mathematical theorems. recognizing patterns, and so on. Recursive algorithms can compute factorials. compute a greatest common divisor. process data structures (strings, vectors, linked lists, etc.). search efficiently using a binary search. find a path through a maze, and more.
15
7.1, pgs. 404-411 7.1 Recursive Thinking
Steps to Design a Recursive Algorithm Proving That a Recursive Function Is Correct Tracing a Recursive Function The Stack and Activation Frames 7.1, pgs
16
Recursive Thinking Recursion Recursion is a problem-solving approach that generates simpler solutions to certain kinds of problems that are difficult to solve by other means. Recursion reduces a problem into one or more simpler versions of itself. For example, consider searching for a target value in a sorted vector: We compare the target to the middle element and, if the middle element does not match the target, search either the elements before the middle element or the elements after the middle element. Instead of searching n elements, we search n/2 elements. Find 23 2 5 8 12 16 23 38 56 72 91 23 > 16, 2nd half 2 5 8 12 16 23 38 56 72 91 23 < 56, 1st half 2 5 8 12 16 23 38 56 72 91 Found 23, Return 5 2 5 8 12 16 23 38 56 72 91
17
Recursive Thinking General Recursive Algorithm:
Recursion General Recursive Algorithm: Step 1 involves a test for what is called the base case: a value of n for which the problem can be solved easily Whenever a split occurs, we revisit Step 1 for each new problem to see whether it is a base case or a recursive case if problem can be solved directly for the current value of n 2. then Solve it. else 3. Recursively apply the algorithm to one or more problems involving smaller values of n. 4. Combine the solutions to the smaller problems to get the solution to the original problem. Step 3 is the recursive case, because there we recursively apply the algorithm Because the value of n for each recursive case is smaller than the original value of n, each recursive case makes progress towards a base case
18
Design a Recursive Algorithm
Recursion Design: Recognize a base case and provide a solution to it. Devise a strategy to split the problem into smaller versions of itself while making progress toward a base case. Combine the solutions to the smaller problems to solve the larger problem. Find the length of a string: /** Recursive function for length of string @param str The string @return The length of the string */ int size(string str) { if (str == "") return 0; return 1 + size(str.substr(1)); }
19
Forward (Example: H e l l o) Reverse (Example: o l l e H)
Pair up. Write a function to recursively print a string of characters (space delimited): Forward (Example: H e l l o) Reverse (Example: o l l e H) /** Recursive function print_chars post: Display in forward order @param str The string */ void print_chars(string str) { } /** Recursive function print_chars_reverse post: Display in reverse order @param str The string */ void print_chars_reverse(string str) { }
20
Printing String Characters
Recursion /** Recursive function print_chars post: The string is displayed @param str The string */ void print_chars(string str) { if (str == "") return; // base case cout << str.at(0); // output 1st character print_chars(str.substr(1)); // output 1 less character } /** Recursive function print_chars_reverse post: Display in reverse order @param str The string */ void print_chars_reverse(string str) { if (str == "") return; // base case print_chars(str.substr(1)); // output 1 less character cout << str.at(0); // output 1st character }
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.