Title: Week 10 b
1Week 10 - b
- Towers of Hanoi
- QuickSort
- Fractals
- 2-Dimensional Recursion
- Review for Final
2Sample Programs Referenced(code located in
course folder)
- Subsets
- Binary Search Redux
- Towers of Hanoi
- BlobApplet
- Merge Sort
- QuickSort
- Sudoku
- MazeExit
3Printing Subsets(problem 3, page 621)
- Set up an array of char to represent a set of
letters - Write a recursive method to print out all subsets
containing exactly 2 elements - Run in BlueJ
- Look at code
4Recursive Binary Search
- Basic algorithm
- If target is middle value, we are done
- Else if target is less than middle value, search
in lower half - Else target is greater than middle value search
in upper half - What about case where target is not in array?
What will happen? - Base case(s)
- Inductive step(s)
5Recursive Binary Search
- public double find(String lookingFor, int first,
int last) - if (first gt last)
- return -1
- else
- next (firstlast)/2
- if (lookingFor.equalsIgnoreCase(nameListnext
)) - return gpaListnext
- else if (lookingFor.compareToIgnoreCase(nameLi
stnext) gt 0) - return find(lookingFor, next1, last)
- else
- return find(lookingFor, first, next-1)
- // end of find method
- If you compare this to the non-recursive version
(week 5), - this recursive version seems easier to
follow!
6Survivor Thailand Episode 3
"Day 9 and it's Immunity Challenge time. It's a
variation of the Hanoi Tower puzzle game. A model
of a Thai temple is made of several stackable
pieces, each smaller than the one below. The
model must be disassembled and re-assembled using
three platforms. They may only stack smaller
pieces on larger ones, and they must be in a
circled area around each platform to move a
piece. This is an easy one for Ted, who knows
math well being a programmer. Chuay Gahn takes an
early lead and never looks back. Shii Ann admits
later that she knew what to do, but kept her
mouth shut. She thinks it's time to get rid of
some people. Sook Jai, under guidance of Jed,
loses their first immunity challenge."
7Towers of Hanoi Game
- Object Move all disks from one platform (pin) to
another platform (pin) - Can only move one disk at a time
- Can't stack larger disk on top of a smaller disk
- Have one additional platform (pin) to use as
auxiliary - (Original problem was for Tibetan Priests to move
64 disks following these rules) - Classic Recursion
- If only one disk to move "Just Do It"
- if not, reduce to simpler problem (one less disk)
- WEB Versions (1), (2), (3)
8Our Problem
- Todays problem is to write a program that
generates the instructions to follow in moving
the disks.
Source
Auxiliary
Destination
9Towers of Hanoi - Client
- User enters number of disks, Program generates a
set of instructions for moving the disks
public class PuzzleClient public static void
main(String args) int numDisks //
number of disks for game numDisks
Integer.parseInt( JOptionPane.showInputDia
log( "Enter the number of disks"))
Puzzle towers new Puzzle()
towers.solve(numDisks) // end of main
method // end of PuzzleClient class
10Towers of Hanoi Puzzle Class
- public class Puzzle
-
- public void solve(int nDisks)
-
- System.out.println("Instructions for solving
the - Towers of Hanoi puzzle for "
- nDisks " disks\n")
- move(nDisks, "A", "C", "B")
-
- ...
-
11Design of the recursive method move
- Lets call the 3 towers Source, Auxiliary,
Destination, - Base case What is an instance of the problem
that is trivial? - n 1
Source
Auxiliary
Destination
Output the instruction to move the top disk from
Source to Destination Move top disk from Source
to Destination
12Design of the recursive method move
- Induction Step n gt 1
- How can recursion help us out?
a. Recursively move n-1 disks from Source to
Auxiliary.
13Design of the recursive method move
- Induction Step n gt 1
- How can recursion help us out?
b. Move the one remaining disk from Source to
Destination.
14Design of the Recursive Function tower()
- Induction Step n gt 1
- How can recursion help us out?
c. Recursively move n-1 disks from Auxiliary to
Destination
15Design of the Recursive Function tower()
- Induction Step n gt 1
- How can recursion help us out?
d. Were done!
16Algorithm
- We can combine these steps into the following
algorithm - 0. Receive n, Source, Auxiliary, Destination
- 1. If n gt 1
- a. Move n-1 disks from Source to Auxiliary
(using Destination) - b. Move 1 disk from Source to Destination
(using Auxiliary) - c. Move n-1 disks from Auxiliary to Destination
(using Source) - Else
- Display Move the top disk from , Source, to
, Destination. - End if.
17Analysis
- Lets see how many moves it takes to solve this
problem, as a function of n. - n Number of disk-moves required
- 1 1
- 2 3
- 3 7
- 4 15
- 5 31
- ...
- i 2i-1
- 64 264-1 (a big number)
18Analysis (Ctd)
- How big?
- Suppose that our computer and super-printer can
generate and print 1,048,576 (220)
instructions/second. - How long will it take to print the instructions
for 64 disks? - There are 264 instructions to print.
- Then it will take 264/220 244 seconds to print
them. - 1 minute 60 seconds.
- Lets take 64 26 as an approximation of 60.
- Then it will take _at_ 244 / 26 238 minutes to
print them.
19Analysis (Ctd)
- 1 hour 60 minutes.
- Lets take 64 26 as an approximation of 60.
- Then it will take _at_ 238 / 26 232 hours to print
them. - 1 day 24 hours.
- Lets take 32 25 as an approximation of 24.
- Then it will take _at_ 232 / 25 227 days to print
them. - 1 year 365 days.
- Lets take 512 29 as an approximation of 365.
- Then it will take _at_ 227 / 29 218 years to print
them. - 1 century 100 years.
- Lets take 128 27 as an approximation of 100.
- Then it will take _at_ 218 / 27 211 centuries to
print them.
20Analysis (Ctd)
- Hmm. 211 centuries is hard to grasp. Lets keep
going... - 1 millenium 10 centuries.
- Lets take 16 24 as an approximation of 10.
- Then it will take _at_ 211 / 24 27 128 millenia
just to print the instructions (assuming our
computer doesnt crash, in which case we have to
start all over again). - How fast can the disks actually be moved?
- Probably NOT one million per second!
- If 1 per second, the task will take more
than128,000,000,000 years
21BlobApplet
- See Textbook, Figure 9.27, page 611
- A Blob consists of gray cells connected
vertically or horizontally - Run in BlueJ, then look at code
22Java BREAK
23Divide-and-Conquer Sort
- Divide and Conquer is more than just a military
strategy, it is also a method of algorithm design
that has created such efficient algorithms as
Merge Sort. - In terms or algorithms, this method has three
distinct steps - Divide If the input size is too large to deal
with in a straightforward manner, divide the data
into two or more disjoint subsets. - Recur Use divide and conquer to solve the
subproblems associated with the data subsets. - Conquer Take the solutions to the subproblems
and merge these solutions into a solution for
the original problem.
24Merge-Sort Algorithm
- Divide If S has at least two elements (nothing
needs to be done if S has zero or one elements),
remove all the elements from S and put them into
two sequences, S1 and S2 , each containing about
half of the elements of S. (i.e. S1 contains the
first n/2 elements and S2 contains the remaining
n/2 elements. - Recur Recursively sort sequences S1 and S2.
- Conquer Put back the elements into S by merging
the sorted sequences S1 and S2 into a unique
sorted sequence.
25Tracing the Merge Algorithm(1 of 2)
26Tracing the Merge Algorithm(2 of 2)
27QuickSort
- To understand quick sort, lets look at a
high-level description of the algorithm - 1) Divide If the sequence S has 2 or more
elements, select an element x from S to be your
pivot. Any arbitrary element, like the last, will
do. Remove all the elements of S and divide them
into 3 sequences - L, holds Ss elements less than x
- E, holds Ss elements equal to x
- G, holds Ss elements greater than x
- 2) Recurse Recursively sort L and G
- 3) Conquer Finally, to put elements back into S
in order, first insert the elements of L, then
those of E, and those of G. - Here are some pretty diagrams....
28Idea of Quick Sort
- 1. Select pick an element (pivot)
2.Divide rearrange elements so that x goes to
its final position E
3. Recurse and Conquer recursively sort
29QuickSort Illustration
30QuickSort Illustration 2
13 19 9 5 12 8 7 4 11 2 6 21
2
4
6
8 9
11
13 19
21
5
7
12
13 19 9 5 12 8 7 4 11 2 6
21
2
4
6
8
11
19
21
5
7
12
9
13
6
5 4 2
13 19 9 12 8 7 11
21
2
4
6
8
11
19
21
5
7
12
9
13
2
4 5
6
9 8 7
11
13 19 12
21
31Quicksort(c.f. Binary Search)
- static void quickSort
- (double A, int lo, int hi)
- int m // pointer to pivot location (mid)
- if (hi gt lo 1) // 3 or more subarray values
- m partition(A, lo, hi)
- quickSort(A, lo, m 1)
- quickSort(A, m 1, hi)
-
- else // less than 3 subarray
values - if ((hi lo 1) (Alo gt Ahi)
- swap(A, lo, hi)
- // end of quickSort method
32Sudoku Solver
- Handout very simple Puzzle
- Go through solving by hand
- Run in BlueJ
- Note backtracking
33A Simple Maze(recursive traversal)
Black Wall Red Path This maze was traversed
from upper left to lower right No diagonal
movements, just Right, Down, Left, Up 2-D array
represents maze in program Recursive
findPath(row, col) looks for path
(data files xmaze.txt and hampton.txt)
34Maze Program Plan
- Read Maze design from a file
- Symbols represent Walls, Start, Finish
- Program can solve more than one maze
- Use 2-D array of some symbols to represent maze
in program - Recursive findPath(row, col) method searches for
solution - Insert Path or Visited symbols in array while
looking for solution - Display method repeatedly shows status of the maze
xmaze.txt file
- 20 20 the X maze
- S..................
- ....
- ..................
- .........
- ................
- ...........
- ..............
- .............
- ............
- .............
- ..............
- ...........
- ............
- .............
- .............
- ...............
- .........
- ................
35findPath(int row, int col)
- Several Base Cases return false or true
- Several Inductive Cases return result of a new
call to findPath with different row column
36findPath(int row, int col)
BASE CASE 1 going off the edge (return
false) BASE CASE 2 already visited, or already
part of the path (return false) BASE CASE 3 had
success got to the finish square (return true)
(mark the square as part of the path) INDUCTIVE
CASE 1 try moving right, see if there is a path
from there INDUCTIVE CASE 2 if that did not work,
try moving down, see if there is a path from
there INDUCTIVE CASE 3 if that did not work, try
moving left, see if there is a path from
there INDUCTIVE CASE 4 if that did not work, try
moving up, see if there is a path from
there (mark the square as visited)
BASE CASE 4 none of the inductive cases worked,
so this space is not part of the path (return
false) (run using "xmaze.txt")
37Hampton Court Maze
A Hedge Maze (nearly 1/3 acre in area) built in
1702 on grounds of Hampton Court Palace near
LondonYou can get lost in it!
Change client and run program with hampton.txt, a
rectangular version of the Hampton Court
Maze Reverse the S and F to get out!
38Recursion Summary
- Recursion is a valuable tool that allows some
problems to be solved in an elegant and efficient
manner. - Methods can sometimes require more than one
recursive call in order to accomplish their task. - There are problems for which we can design a
solution, but the nature of the problem makes
solving it effectively uncomputable. (e.g. Towers
of Hanoi for 64 disks)
39Remember
- Must have a "base" case
- Must work toward the base case by simplifying the
problem each time - Use if, not while since the recursion itself is
performing a "loop"
40Review for FinalSample Final
- GUI
- Frames, Panels, Buttons, Labels, TextBoxes,
CheckBoxes, RadioButtons - Events
- ActionListener, ItemListener, MouseListener
- Layout Managers
- FlowLayout, BorderLayout, GridLayout
- Exceptions
- try/catch/finally
- External Files
- Readers/Writers
- Recursion
- base case, inductive step
41Course Assessment
- Please Complete Form to help us improve the
course
42The END