Professional Documents
Culture Documents
S E D G E W I C K / W A Y N E
PA R T I : P R O G R A M M I N G I N J AVA
Computer Science
Computer 6. Recursion
ScienceAn Interdisciplinary Approach
ROBERT SEDGEWICK
Section 2.3 K E V I N WAY N E
http://introcs.cs.princeton.edu
COMPUTER SCIENCE
S E D G E W I C K / W A Y N E
PA R T I : P R O G R A M M I N G I N J AVA
6. Recursion
• Foundations
• A classic example
• Recursive graphics
• Avoiding exponential waste
• Dynamic programming
CS.6.A.Recursion.Foundations
Overview
Q. What is recursion?
4
Mathematical induction (quick review)
5
Proving a recursive program correct
• Base case. Return a value for small N . • Base case. Prove it for small N.
• Reduction step. Assuming that it works for • Induction step. Assuming that the
smaller values of its argument, use the statement is true for all positive integers
function to compute a return value for N. less than N, use that fact to prove it for N.
6
Mechanics of a function call
Try N = 2
need to know
Both lead to infinite recursive loops (bad news). how to stop them
on your computer
8
Collatz Sequence
Collatz function of N.
• If N is 1, stop.
• If N is even, divide by 2. 7 22 11 34 17 52 26 13 49 20 ...
• If N is odd, multiply by 3 and add 1.
Amazing fact. No one knows whether or not this function terminates for all N (!)
Note. We usually ensure termination by only making recursive calls for smaller N.
9
COMPUTER SCIENCE
S E D G E W I C K / W A Y N E
PA R T I : P R O G R A M M I N G I N J AVA
6. Recursion
• Foundations
• A classic example
• Recursive graphics
• Avoiding exponential waste
• Dynamic programming
CS.6.B.Recursion.Hanoi
Warmup: subdivisions of a ruler (revisited)
ruler(4) 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1
ruler(3) 1 2 1 3 1 2 1 1 2 1 3 1 2 1
ruler(2) 1 2 1 1 2 1 1 2 1 1 2 1
ruler(1) 1 1 1 1 1 1 1 1
ruler(0) ⎵ ⎵ ⎵ ⎵ ⎵ ⎵ ⎵ ⎵ ⎵ ⎵ ⎵ ⎵ ⎵ ⎵ ⎵ ⎵
14
Towers of Hanoi puzzle
n = 10
Rules
• Move discs one at a time. before
• Never put a larger disc on a smaller disc.
15
Towers of Hanoi
0 1 2
1 2 3
A recursive solution
• Move n 1 discs to the left (recursively).
• Move largest disc to the right.
• Move n 1 discs to the left (recursively).
16
Towers of Hanoi solution (n = 3)
1R
2L
1R
3R
1R
1R 2L 1R 3R 1R 2L 1R 2L
1R
17
Towers of Hanoi: recursive solution
18
Recursive call tree for towers of Hanoi
Structure is the same as for the ruler function and suggests 3 useful and easy-to-prove facts.
• Each disc always moves in the same direction.
• Moving smaller disc always alternates with a unique legal move.
• Moving n discs requires 2n 1 moves.
hanoi(4, true)
1 2 1 3 1 2 1 4 1 2 1 3 1 2 1
R L R R R L R L R L R R R L R
hanoi(3, false)
1 2 1 3 1 2 1 1 2 1 3 1 2 1
R L R R R L R R L R R R L R
hanoi(2, true)
1 2 1 1 2 1 1 2 1 1 2 1
R L R R L R R L R R L R
hanoi(1, false)
1 1 1 1 1 1 1 1
R R R R R R R R
hanoi(0, true)
⎵ ⎵ ⎵ ⎵ ⎵ ⎵ ⎵ ⎵ ⎵ ⎵ ⎵ ⎵ ⎵ ⎵ ⎵ ⎵
19
Answers for towers of Hanoi
A. (Short form). Alternate "1L" with the only legal move not involving the disc 1.
"L" or "R" depends on whether n is odd or even
20
COMPUTER SCIENCE
S E D G E W I C K / W A Y N E
PA R T I : P R O G R A M M I N G I N J AVA
6. Recursion
• Foundations
• A classic example
• Recursive graphics
• Avoiding exponential waste
• Dynamic programming
CS.6.C.Recursion.Graphics
Recursive graphics in the wild
23
"Hello, World" of recursive graphics: H-trees
H-tree of order n
• If n is 0, do nothing.
• Draw an H, centered.
• Draw four H-trees of order n 1 and half the size, centered at the tips of the H.
24
H-trees
Application. Connect
a large set of
order 6
1
2
3
4
5
regularly spaced sites
to a single source.
25
Recursive H-tree implementation
sz
public class Htree
{ y1
public static void draw(int n, double sz, double x, double y)
{
if (n == 0) return;
double x0 = x - sz/2, x1 = x + sz/2;
y
double y0 = y - sz/2, y1 = y + sz/2;
StdDraw.line(x0, y, x1, y);
StdDraw.line(x0, y0, x0, y1); draw the H,
centered on (x, y )
StdDraw.line(x1, y0, x1, y1);
draw(n-1, sz/2, x0, y0); y0
draw(n-1, sz/2, x0, y1); draw four
draw(n-1, sz/2, x1, y0); half-size H-trees
draw(n-1, sz/2, x1, y1); x0 x x1
}
public static void main(String[] args) % java Htree 3
{
int n = Integer.parseInt(args[0]);
draw(n, .5, .5, .5);
}
}
26
Deluxe H-tree implementation
27
Fractional Brownian motion
28
Fractional Brownian motion simulation
• Consider a line segment from (x0, y0) to (x1, y1). δ (x1, y1)
• If sufficiently short draw it and return
• Divide the line segment in half, at (xm, ym). (xm, ym )
• Choose δ at random from Gaussian distribution.
(x0, y0)
• Add δ to ym.
• Recur on the left and right line segments.
29
Brownian motion implementation
30
A 2D Brownian model: plasma clouds
0 10 20
30 49 60
60 80 100 31
A Brownian cloud
32
A Brownian landscape
33
COMPUTER SCIENCE
S E D G E W I C K / W A Y N E
PA R T I : P R O G R A M M I N G I N J AVA
6. Recursion
• Foundations
• A classic example
• Recursive graphics
• Avoiding exponential waste
• Dynamic programming
CS.6.D.Recursion.Waste
Fibonacci numbers
n 0 1 2 3 4 5 6 7 8 9 10 11 12 13 ...
Fn 0 1 1 2 3 5 8 13 21 34 55 89 144 233 ...
Models many natural phenomena and is widely found in art and architecture. Leonardo Fibonacci
c. 1170 – c. 1250
Examples.
golden ratio Fn / Fn 1
• Model for reproducing rabbits.
• Nautilus shell.
8
• Mona Lisa.
21
• ...
13
Facts (known for centuries).
• Fn / Fn 1 ➛ ⇤ = 1.618... as n ➛ ∞
21 13
• Fn is the closest integer to ⇤n/√5
36
Fibonacci numbers and the golden ratio in the wild
1
1
2
1 3
1 1 5
8
1 2 1
13
1 3 3 1 21
1 4
6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
37
Computing Fibonacci numbers
A. [Novice programmer.] Just a second. I'll write a recursive program to compute it.
38
Recursive call tree for Fibonacci numbers
F(6)
8
F(5)
5
F(4)
3 3
F(3) 2
2 2
F(2)
1 1 1 1 1
F(1)
1 1 1 1 1 1 1 1
F(0)
0 0 0 0 0
39
Exponential waste
n Cn
F(60)
60 1 F1
F(59)
59 1 F2
F(58) F(58)
58 2 F3
F(57) F(57)
57 3 F4
F(56)
56 5 F5
F(55)
55 8 F6
... ...
If you engage in exponential waste, you will not be able to solve a large problem.
30 minutes 50 minutes
Macbook Air
40 hours 60 hours
50 weeks 70 weeks
60 years 80 years
VAX 11/780 70 centuries 90 centuries
80 millenia 100 millenia
1970s: "That program won't compute F60 before you graduate! "
2010s: "That program won't compute F80 before you graduate! "
41
Avoiding exponential waste
7. Recursion
• Foundations
• A classic example
• Recursive graphics
• Avoiding exponential waste
• Dynamic programming
CS.6.E.Recursion.DP
An alternative to recursion that avoids recomputation
Dynamic programming.
• Build computation from the "bottom up".
• Solve small subproblems and save solutions.
• Use those solutions to build bigger solutions.
Richard Bellman
Fibonacci numbers public class Fibonacci 1920-1984
{
public static void main(String[] args)
{ % java Fibonacci 50
int n = Integer.parseInt(args[0]); 12586269025
long[] F = new long[n+1]; % java Fibonacci 60
F[0] = 0; F[1] = 1; 1548008755920
for (int i = 2; i <= n; i++) % java Fibonacci 80
F[i] = F[i-1] + F[i-2]; 23416728348467685
StdOut.println(F[n]);
}
}
Key advantage over recursive solution. Each subproblem is addressed only once.
45
DP example: Longest common subsequence
Ex 1. s = ggcaccacg Ex 2. t = acggcggatacg
cac ggcaccacg gacg acggcggatacg
gcaacg ggcaccacg ggggg acggcggatacg
ggcaacg ggcaccacg cggcgg acggcggatacg
ggcacacg ggcaccacg ggcaacg acggcggatacg
... ggggaacg acggcggatacg
...
[2n subsequences in a string of length n]
Def. The LCS of s and t is the longest string that is a subsequence of both.
Goal. Efficient algorithm to compute the LCS and/or its length numerous scientific applications
46
Longest common subsequence
Goal. Efficient algorithm to compute the length of the LCS of two strings s and t.
Approach. Keep track of the length of the LCS of s[i..M) and t[j..N) in opt[i, j]
Ex: i = 6, j = 7
s[6..9) = acg
t[7..12) = atacg
Three cases: LCS(cg, tacg) = cg
• i = M or j = N
LCS(acg, atacg) = acg
opt[i][j] = 0
• s[i] = t[j]
Ex: i = 6, j = 4
opt[i][j] = opt[i+1, j+1] + 1
s[6..9) = acg
• otherwise
t[4..12) = cggatacg
opt[i][j] = max(opt[i, j+1], opt[i+1][j]) LCS(acg, ggatacg) = acg
LCS(cg, cggatacg) = cg
LCS(acg, cggatacg) = acg
47
LCS example
0 1 2 3 4 5 6 7 8 9 10 11 12
a c g g c g g a t a c g
0 g 7 7 7 6 6 6 5 4 3 3 2 1 0
1 g 6 6 6 6 5 5 5 4 3 3 2 1 0
2 c 6 5 5 5 5 4 4 4 3 3 2 1 0
3 a 6 5 4 4 4 4 4 4 3 3 2 1 0
4 c 5 5 4 4 4 3 3 3 3 3 2 1 0
5 c 4 4 4 4 4 3 3 3 3 3 2 1 0 opt[i][j] = max(opt[i, j+1], opt[i+1][j])
7 c 2 2 2 2 2 2 2 2 2 2 2 1 0
8 g 1 1 1 1 1 1 1 1 1 1 1 1 0
9 0 0 0 0 0 0 0 0 0 0 0 0 0
48
LCS length implementation
Exercise. Add code to print LCS itself (see LCS.java on booksite for solution).
49
Dynamic programming and recursion
50