2 3 Recursion With notes by Ron Cytron
2. 3 Recursion With notes by Ron Cytron shown like this. Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2002– 2010 · 12/25/2021 5: 11: 07 AM
Overview What is recursion? When one function calls itself directly or indirectly. Why learn recursion? New mode of thinking. Powerful programming paradigm. n n Many computations are naturally self-referential. Mergesort, FFT, gcd, depth-first search. Linked data structures. A folder contains files and other folders. n n n Closely related to mathematical induction. Reproductive Parts M. C. Escher, 1948 2
Greatest Common Divisor Gcd. Find largest integer that evenly divides into p and q. Ex. gcd(4032, 1272) = 24. 4032 = 26 32 71 1272 = 23 31 531 gcd = 23 31 = 24 While this is a good example of recursion, it is not the best place to start. I’m going to go through some of Ken Goldman’s slides, which use factorial as an example. IMHO it’s a better place to start. Applications. Simplify fractions: 1272/4032 = 53/168. RSA cryptosystem. n n 3
Greatest Common Divisor Gcd. Find largest integer d that evenly divides into p and q. Euclid's algorithm. [Euclid 300 BCE] base case reduction step, converges to base case gcd(4032, 1272) = = = gcd(1272, 216) gcd(216, 192) gcd(192, 24) gcd(24, 0) 24. 4032 = 3 1272 + 216 4
Greatest Common Divisor Gcd. Find largest integer d that evenly divides into p and q. base case reduction step, converges to base case p q q x x x p = 8 x q = 3 x gcd(p, q) = x p % q x x x gcd 5
Greatest Common Divisor Gcd. Find largest integer d that evenly divides into p and q. base case reduction step, converges to base case Java implementation. public static int gcd(int p, int q) { if (q == 0) return p; else return gcd(q, p % q); } base case reduction step 6
Recursive Graphics
9
Htree H-tree of order n. n n and half the size Draw an H. Recursively draw 4 H-trees of order n-1, one connected to each tip size order 1 order 2 order 3 10
Htree in Java public class Htree { public static void draw(int n, double sz, double x, double y) { if (n == 0) return; double x 0 = x - sz/2, x 1 = x + sz/2; double y 0 = y - sz/2, y 1 = y + sz/2; Std. Draw. line(x 0, y, x 1, y); Std. Draw. line(x 0, y 0, x 0, y 1); Std. Draw. line(x 1, y 0, x 1, y 1); draw the H, centered on (x, y) draw(n-1, recursively draw 4 half-size Hs sz/2, x 0, x 1, y 0); y 1); } public static void main(String[] args) { int n = Integer. parse. Int(args[0]); draw(n, . 5, . 5); } } 11
Animated H-tree. Pause for 1 second after drawing each H. 20% 40% 60% 80% 100% 12
Towers of Hanoi http: //en. wikipedia. org/wiki/Image: Hanoiklein. jpg
Towers of Hanoi Move all the discs from the leftmost peg to the rightmost one. Only one disc may be moved at a time. A disc can be placed either on empty peg or on top of a larger disc. n n start finish Towers of Hanoi demo Edouard Lucas (1883) 14
Towers of Hanoi Legend Q. Is world going to end (according to legend)? 64 golden discs on 3 diamond pegs. World ends when certain group of monks accomplish task. n n Q. Will computer algorithms help? 15
Towers of Hanoi: Recursive Solution 1 2 Left of leftmost pole…. Move n-1 smallest discs right. Move largest disc left. 3 4 cyclic wrap-around …wraps around to rightmost pole Move n-1 smallest discs right. 16
Towers of Hanoi: Recursive Solution public class Towers. Of. Hanoi { public static void moves(int n, boolean left) { if (n == 0) return; moves(n-1, !left); if (left) System. out. println(n + " left"); else System. out. println(n + " right"); moves(n-1, !left); } public static void main(String[] args) { int N = Integer. parse. Int(args[0]); moves(N, true); } } moves(n, true) : move discs 1 to n one pole to the left moves(n, false): move discs 1 to n one pole to the right smallest disc 17
Towers of Hanoi: Recursive Solution % 1 2 1 3 1 2 1 java Towers. Of. Hanoi 3 left right left every other move is smallest disc % 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 java Towers. Of. Hanoi 4 right left right right left right subdivisions of ruler 18
Towers of Hanoi: Recursion Tree L, R, M show the absolute pole Assume 3 disks on L “To the left” “To the right” are relative terms n, left To move 3 disks to the left by one pole (R)… 3, true Move disks 1. . 2 to the right (M), to 1 get them out of the way. Move disks 1. . 2 to the right, again. 28 on the middle pole. When 15 were They we come back, the will be on R, atop disk 3 14 2, false 2 8 7 1, true 3 4 5 2, false 16 13 1, true 6 9 10 21 22 27 1, true 17 18 11 12 19 20 23 24 25 26 Move disk 3 to the left. (R) 1 left 2 right 1 left 3 left 1 left 2 right 1 left 19
Towers of Hanoi: Recursion Tree Assume 3 disks on the left pole, moving left again, from L to R n, left 3, true Done! 1 and 2 are now on M To move 1… 2 to from L to M 1 14 28 15 2, false 2 Move 1 to the left (R) 7 8 5 16 13 Move 1 left again, from R to M 1, true 3 4 2, false 1, true 6 9 10 21 22 27 1, true 17 18 11 12 19 20 23 24 25 26 Move 2 to M 1 left 2 right 1 left 3 left 1 left 2 right 1 left 20
Towers of Hanoi: Recursion Tree Done Assume 3 disks on the left pole, moving left again, from L to R n, left 3, true Done! 1 and 2 are now on M 1 Done, 1… 2 now on R 14 28 15 Move 1. . 2 to the right, from M to R 2, false 2 8 7 1, true 3 4 5 2, false 13 Move 1 to L 1, true 6 9 10 16 2 right 17 18 11 12 1 left 22 27 1, true 19 20 3 left 23 24 Move 2 to R, now atop 3 Move 3 to R 1 left 21 1 left 2 right 25 26 Move 1 left, from L to R 1 left 21
Towers of Hanoi: Properties of Solution Remarkable properties of recursive solution. Takes 2 n - 1 moves to solve n disc problem. Sequence of discs is same as subdivisions of ruler. Every other move involves smallest disc. n n n Recursive algorithm yields non-recursive solution! Alternate between two moves: to left if n is odd – move smallest disc to right if n is even – make only legal move not involving smallest disc n Recursive algorithm may reveal fate of world. Takes 585 billion years for n = 64 (at rate of 1 disc per second). Reassuring fact: any solution takes at least this long! n n 22
Divide-and-Conquer Divide-and-conquer paradigm. Break up problem into smaller subproblems of same structure. Solve subproblems recursively using same method. Combine results to produce solution to original problem. n n n Divide et impera. Veni, vidi, vici. - Julius Caesar Many important problems succumb to divide-and-conquer. n n n n FFT for signal processing. Parsers for programming languages. Multigrid methods for solving PDEs. Quicksort and mergesort for sorting. Hilbert curve for domain decomposition. Quad-tree for efficient N-body simulation. Midpoint displacement method for fractional Brownian motion. 23
New slides by RKC Two ways of thinking about recursion Way 1: You are given a recursive formula, and you just need to implement it in code. Example: fact(n) = n * fact(n-1) fact(n) = 1 if n > 0 if n == 0 (function’s value is undefined if n is negative) public static int fact(n) { if (n==0) return 1; else return n * fact(n-1); } // I tend to put base case first 24
New slides by RKC Two ways of thinking about recursion Way 2: You are given a sketch of the computation and you must find the recursive substructure fact(n) = n x (n-1) x (n-2) x … x 1 fact(n-1) = (n-1) x (n-2) x … x 1 The computation in the box is therefore fact(n-1). This is the act of finding substructure in the computation. We found something smaller than the original fact(n) that can be computed using the same function. Think of the function’s expansion as just a string of symbols. A call to fact(n) spews out the text shown in the box. fact(n) = n * fact(n-1) Still need special case: fact(0) = 1 25
Substitution model for recursive evaluation New slides by RKC public static int fact(n) { if (n==0) return 1; else return n * fact(n-1); } // I tend to put base case first fact(3) = 3 * fact(3 -1) = 3 * fact(2) = 3 * 2 * fact(2 -1) = 3 * 2 * fact(1) = 3 * 2 * 1 * fact(1 -1) = 3 * 2 * 1 * fact(0) =3*2*1*1 =3*2 =6 26
Substitution model for recursive evaluation New slides by RKC public static int mys(n) { if (n==0) return 0; else return n – mys(n-1); } // I tend to put base case first mys(3) = 3 – mys(2) = 3 – 2 – mys(1) = 3 – 2 – 1 – mys(0) =3– 2– 1 -0 …. =0 ? 27
Substitution model for recursive evaluation New slides by RKC public static int mys(n) { if (n==0) return 0; else return n – mys(n-1); } // I tend to put base case first mys(3) = 3 – mys(2) = 3 – 2 – mys(1) = 3 – 2 – 1 – mys(0) =3– 2– 1– 0 mys(0) = 0 =3– 2– 1 =3– 1 =2 mys(1) = 1 -0 = 1 mys(2) = 2 -1 = 1 28
Fibonacci Numbers
Fibonacci Numbers Fibonacci numbers. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, … L. P. Fibonacci (1170 - 1250) Fibonacci rabbits 30
Fibonacci Numbers and Nature Fibonacci numbers. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, … pinecone cauliflower 31
A Possible Pitfall With Recursion Fibonacci numbers. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, … A natural for recursion? public static long F(int n) { if (n == 0) return 0; if (n == 1) return 1; return F(n-1) + F(n-2); } 32
Recursion Challenge 1 (difficult but important) Q. Is this an efficient way to compute F(50)? public static long F(int n) { if (n == 0) return 0; if (n == 1) return 1; return F(n-1) + F(n-2); } A. No, no! This code is spectacularly inefficient. F(50) is called once. F(49) F(48) F(49) is called once. F(48) F(47) F(46) F(47) F(45) F(46) F(45) F(44) F(48) is called 2 times. F(47) is called 3 times. F(46) is called 5 times. F(45) is called 8 times. . recursion tree for naïve Fibonacci function F(1) is called 12, 586, 269, 025 times. F(50) 33
Recursion Challenge 2 (easy and also important) Q. Is this a more efficient way to compute F(50)? public static long F(int n) { if (n == 0) return 0; long[] F = new long[n+1]; F[0] = 0; F[1] = 1; for (int i = 2; i <= n; i++) F[i] = F[i-1] + F[i-2]; return F[n]; } FYI: classic math = golden ratio 1. 618 A. Yes. This code does it with 50 additions. Lesson. Don’t use recursion to engage in exponential waste. Context. This is a special case of an important programming technique known as dynamic programming (stay tuned). 34
Summary How to write simple recursive programs? Base case, reduction step. Trace the execution of a recursive program. Use pictures. n n n Why learn recursion? New mode of thinking. Powerful programming tool. Towers of Hanoi by W. A. Schloss. n n Divide-and-conquer. Elegant solution to many important problems. 35
Extra Slides
Collatz Sequence Collatz sequence. If n is 1, stop. If n is even, divide by 2. If n is odd, multiply by 3 and add 1. n n n Ex. 35 106 53 160 80 40 20 10 5 16 8 4 2 1. public static void collatz(int n) { System. out. print(n + " "); if (n == 1) return; if (n % 2 == 0) collatz(n / 2); collatz(3*n + 1); } 37
Fractional Brownian Motion
Fractional Brownian Motion Physical process which models many natural and artificial phenomenon. Price of stocks. Dispersion of ink flowing in water. Rugged shapes of mountains and clouds. Fractal landscapes and textures for computer graphics. n n 39
Simulating Brownian Motion Midpoint displacement method. Maintain an interval with endpoints (x 0, y 0) and (x 1, y 1). Divide the interval in half. Choose at random from Gaussian distribution. Set xm = (x 0 + x 1)/2 and ym = (y 0 + y 1)/2 + . Recur on the left and right intervals. n n n 40
Simulating Brownian Motion: Java Implementation Midpoint displacement method. Maintain an interval with endpoints (x 0, y 0) and (x 1, y 1). Divide the interval in half. Choose at random from Gaussian distribution. Set xm = (x 0 + x 1)/2 and ym = (y 0 + y 1)/2 + . Recur on the left and right intervals. n n n public static void curve(double x 0, double y 0, double x 1, double y 1, double var) { if (x 1 - x 0 < 0. 01) { Std. Draw. line(x 0, y 0, x 1, y 1); return; } double xm = (x 0 + x 1) / 2; double ym = (y 0 + y 1) / 2; ym += Std. Random. gaussian(0, Math. sqrt(var)); curve(x 0, y 0, xm, ym, var/2); variance halves at each level; curve(xm, ym, x 1, y 1, var/2); change factor to get different shapes } 41
Plasma Cloud Plasma cloud centered at (x, y) of size s. Each corner labeled with some grayscale value. Divide square into four quadrants. The grayscale of each new corner is the average of others. – center: average of the four corners + random displacement – others: average of two original corners Recur on the four quadrants. n n c 1 c 2 c 3 c 4 42
Plasma Cloud 43
Brownian Landscape Reference: http: //www. geocities. com/aaron_torpy/gallery. htm 44
Brown Robert Brown (1773 -1858) 45
Brownian Motion (Brown University Men’s Ultimate Frisbee Team) 46
- Slides: 45