Recursion continued Exercise solution // Returns base ^ exponent. - - PowerPoint PPT Presentation

recursion continued exercise solution
SMART_READER_LITE
LIVE PREVIEW

Recursion continued Exercise solution // Returns base ^ exponent. - - PowerPoint PPT Presentation

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 =


slide-1
SLIDE 1

Recursion continued

slide-2
SLIDE 2

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); } }

slide-3
SLIDE 3

3

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

slide-4
SLIDE 4

4

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!

slide-5
SLIDE 5

An optimization

 Notice the following mathematical property:

312 = (32)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.

slide-6
SLIDE 6

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); } }

slide-7
SLIDE 7

7

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

slide-8
SLIDE 8

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?

slide-9
SLIDE 9

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?

slide-10
SLIDE 10

Binary search

binarySearch(dictionary, word){ if (dictionary has one page) {// base case scan the page for word } else {// recursive case

  • pen 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) } }

slide-11
SLIDE 11

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

int index = binarySearch(data, 42); // 10 int index2 = binarySearch(data, 66); // -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

slide-12
SLIDE 12

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

  • ld.

Thereafter each pair produces another pair each month

Rabbits never die.

 How many pairs will there be after n

months?

12

image from: http://www.jimloy.com/algebra/fibo.htm

slide-13
SLIDE 13

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?

slide-14
SLIDE 14

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 mn = mn-1 (rabbits never die) + mn-2 (newborn pairs) How fast does this rabbit population grow?

slide-15
SLIDE 15

Fibonacci numbers

 The Fibonacci numbers are a sequence of

numbers F0, F1, ... Fn defined by: F0 = F1 = 1 Fi = Fi-1 + Fi-2 for any i > 1

 Write a method that, when given an integer i,

computes the nth Fibonacci number.

slide-16
SLIDE 16

16

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

slide-17
SLIDE 17

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 F3 F2 F0 F1 F4 F1 F3 F2 F0 F1 F1 F2 F0 F1

slide-18
SLIDE 18

Growth of rabbit population

1 1 2 3 5 8 13 21 34 ... every 2 months the population at least DOUBLES

slide-19
SLIDE 19

19

Recursive Algorithms

Example: Tower of Hanoi, move all disks to third peg without ever placing a larger disk on a smaller one.

slide-20
SLIDE 20

Try to find the pattern by cases

 One disk is easy  Two disks...  Three disks...  Four disk...

slide-21
SLIDE 21

21

Recursive Algorithms

Example: Tower of Hanoi, move all disks to third peg without ever placing a larger disk on a smaller one.

slide-22
SLIDE 22

22

Recursive Algorithms

Example: Tower of Hanoi, move all disks to third peg without ever placing a larger disk on a smaller one.

slide-23
SLIDE 23

23

Recursive Algorithms

Example: Tower of Hanoi, move all disks to third peg without ever placing a larger disk on a smaller one.

slide-24
SLIDE 24

24

Recursive Algorithms

Example: Tower of Hanoi, move all disks to third peg without ever placing a larger disk on a smaller one.

slide-25
SLIDE 25

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

slide-26
SLIDE 26

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)

slide-27
SLIDE 27

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)

slide-28
SLIDE 28

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

slide-29
SLIDE 29

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?

slide-30
SLIDE 30

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

slide-31
SLIDE 31

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)

slide-32
SLIDE 32

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;