Recursion continued
Exercise solution // Returns base ^ exponent. // Precondition: exponent >= 0 public static int pow(int x, int n) { if (n == 0) { // base case; any number to 0th power is 1 return 1; } else { // recursive case: x^n = x * x^(n-1) return x * pow(x, n-1); } }
How recursion works Each call sets up a new instance of all the parameters and the local variables When the method completes, control returns to the method that invoked it (which might be another invocation of the same method) pow(4, 3) = 4 * pow(4, 2) = 4 * 4 * pow(4, 1) = 4 * 4 * 4 * pow(4, 0) = 4 * 4 * 4 * 1 = 64 3
Infinite recursion A method with a missing or badly written base case can causes infinite recursion public static int pow(int x, int y) { return x * pow(x, y - 1); // Oops! Forgot base case } pow(4, 3) = 4 * pow(4, 2) = 4 * 4 * pow(4, 1) = 4 * 4 * 4 * pow(4, 0) = 4 * 4 * 4 * 4 * pow(4, -1) = 4 * 4 * 4 * 4 * 4 * pow(4, -2) = ... crashes: Stack Overflow Error! 4
An optimization Notice the following mathematical property: 3 12 = (3 2 ) 6 = (9) 6 = (81) 3 = 81*(81) 2 How does this "trick" work? Do you recognize it? How can we incorporate this optimization into our pow method? What is the benefit of this trick? Go write it.
Exercise solution 2 // Returns base ^ exponent. // Precondition: exponent >= 0 public static int pow(int base, int exponent) { if (exponent == 0) { // base case; any number to 0th power is 1 return 1; } else if (exponent % 2 == 0) { // recursive case 1: x^y = (x^2)^(y/2) return pow(base * base, exponent / 2); } else { // recursive case 2: x^y = x * x^(y-1) return base * pow(base, exponent - 1); } }
Activation records activation record : memory that Java allocates to store information about each running method return point ("RP"), argument values, local variable values Java stacks up the records as methods are called; a method's activation record exists until it returns Eclipse debug draws the act. records and helps us trace the behavior of a recursive method _ | x = [ 4 ] n = [ 0 ] | pow(4, 0) | RP = [pow(4,1)] | | x = [ 4 ] n = [ 1 ] | pow(4, 1) | RP = [pow(4,2)] | | x = [ 4 ] n = [ 2 ] | pow(4, 2) | RP = [pow(4,3)] | | x = [ 4 ] n = [ 3 ] | pow(4, 3) | RP = [main] | | | main 7
Factorial What is the formula for the factorial of a number? How would you write that recursively? What is the base case? What is the recursive case?
Dictionary lookup Suppose you’re looking up a word in the dictionary (paper one, not online!) You probably won’t scan linearly thru the pages – inefficient. What would be your strategy?
Binary search binarySearch(dictionary, word){ if (dictionary has one page) { // base case scan the page for word } else { // recursive case open the dictionary to a point near the middle determine which half of the dictionary contains word if (word is in first half of the dictionary) { binarySearch(first half of dictionary, word) } else { binarySearch(second half of dictionary, word) } }
Binary search Write a method binarySearch that accepts a sorted array of integers and a target integer and returns the index of an occurrence of that value in the array. If the target value is not found, return -1 index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 value -4 2 7 10 15 20 22 25 30 36 42 50 56 68 85 92 103 int index = binarySearch(data, 42); // 10 int index2 = binarySearch(data, 66); // -1
Fibonacci’s Rabbits Suppose a newly-born pair of rabbits, one male, one female, are put on an island. A pair of rabbits doesn’t breed until 2 months old. Thereafter each pair produces another pair each month Rabbits never die. How many pairs will there be after n months? image from: http://www.jimloy.com/algebra/fibo.htm 12
Do some cases, see a pattern? m0: 1 young 1 m1: 1 mature 1 m2: 1 mature 1 young 2 m3: 2 mature 1 young 3 m4: 3 mature 2 young 5 m5: 5 mature 3 young 8 m6?
The pattern... m0: 1 young 1 m1: 1 mature 1 m2: 1 mature 1 young 2 m3: 2 mature 1 young 3 m4: 3 mature 2 young 5 m n = m n-1 (rabbits never die) + m n-2 (newborn pairs) How fast does this rabbit population grow?
Fibonacci numbers The Fibonacci numbers are a sequence of numbers F 0 , F 1 , ... F n defined by: F 0 = F 1 = 1 F i = F i -1 + F i -2 for any i > 1 Write a method that, when given an integer i , computes the nth Fibonacci number.
Fibonacci numbers recursive Fibonacci was expensive because it made many, many recursive calls fibonacci(n) recomputed fibonacci(n-1, ... ,1) many times in finding its answer! this is a common case of "overlapping subproblems ”, where the subtasks handled by the recursion are redundant with each other and get recomputed 16
Fibonacci code Let's run it for n = 1,2,3,... 10, ... , 20,... What happens if n = 5, 6, 7, 8, ... Every time n increments with 2, the call tree more than doubles.. F5 F4 F3 F2 F1 F2 F3 F0 F1 F1 F2 F1 F0 F0 F1
Growth of rabbit population 1 1 2 3 5 8 13 21 34 ... every 2 months the population at least DOUBLES
Recursive Algorithms Example: Tower of Hanoi, move all disks to third peg without ever placing a larger disk on a smaller one. 19
Try to find the pattern by cases One disk is easy Two disks... Three disks... Four disk...
Recursive Algorithms Example: Tower of Hanoi, move all disks to third peg without ever placing a larger disk on a smaller one. 21
Recursive Algorithms Example: Tower of Hanoi, move all disks to third peg without ever placing a larger disk on a smaller one. 22
Recursive Algorithms Example: Tower of Hanoi, move all disks to third peg without ever placing a larger disk on a smaller one. 23
Recursive Algorithms Example: Tower of Hanoi, move all disks to third peg without ever placing a larger disk on a smaller one. 24
Parade A parade consists of a set of bands and floats in a single line. To keep from drowning each other out, bands cannot be placed next to another band Given the parade is of length n, how many ways can it be organized
Counting ways Let P(n) = the number of ways the parade can be organized. Parades can either end in a band or a float Let F(n) = the number of parades of length n ending in a float Let B(n) = the number of parades of length n ending in a band So: P(n) = F(n) + B(n)
Recursive case Consider F(n) Since a float can be placed at next to anything, the number of parades ending in a float is equal to F(n) = P(n-1) Consider B(n) The only way a band can end a parade is if the next to last unit is a float. B(n) = F(n-1) By substitution, B(n) = P(n-2) So: P(n) = P(n-1) + P(n-2)
Base case How many parades configs can there be for: n=1 2 – float or band How many parade configs can there be for : n=2 3 Float/float Band/float Float/band
Spock’s dilemma We’ve reached the end of the 5 year mission, just a few days to go The Enterprise enters a new solar system – which has n planets Unfortunately, we only have time to visit k of those planets How many different choices are there?
The algorithm Let c(n,k) = the number of choices Let us consider a planet X C(n,k) = the number of choices that include choosing planet X + the number of choices that do not include planet X
The recurring cases Including planet X C(n-1, k-1) Not including planet X C(n-1, k) So: C(n,k) = C(n-1,k-1) + C(n-1, k)
The base cases If k=0 We have chosen all the planets we can choose What’s left is a single case If k = n We must choose all the remaining planets What’s left is a single case So: If (k == 0) || (k == n) return 1;
Recommend
More recommend