Presentation is loading. Please wait.

Presentation is loading. Please wait.

Recursion Chapter 11.

Similar presentations


Presentation on theme: "Recursion Chapter 11."— Presentation transcript:

1 Recursion Chapter 11

2 Recursion Review of Methods Fractal Images What is Recursion
Recursive Algorithms with Simple Variables Towers of Hanoi

3 Methods Named set of instructions
name suggests what the instructions are for println  print a line nextInt  get the next int setName  change the name what do you suppose these methods do? sort shuffle drawFern

4 The Job of the Method Every method has a job to do
print a line, get the next int, draw a fern, … (part of the job may be signalling errors) Call the method  the job gets done that’s what the method is there for How the method does the job… the body/definition of the method …is none of the caller’s business!

5 Doing The Job The method does the job How?
…println(“Hello”)  “Hello” gets printed …nextInt()  next int appears …sort(myArr)  myArr gets sorted How? doesn’t matter! tomorrow it could do it a different way just matters that the job gets done

6 Arguments and Parameters
Methods often need extra information what do you want me to print on the line? what do you want me to change the name to? which array do you want to sort/shuffle? Extra information given as an argument buddy.setName(“Buford”); Extra information received as a parameter public void setName(String newName) { …}

7 Arguments and Parameters
Assignment call is like assignment buddy.setName(“Buford”); public void setName(String newName) { …} String newName = “Buford” Arguments and parameters must match up String parameter needs a String argument int parameter needs an int argument argument order must match parameter order the computer cannot figure it out on its own!

8 Arguments and Parameters
Different arguments in different calls printArr(arr1)  prints arr1 printArr (arr2)  prints arr2 Same parameter every time public static void printArr(int[] arr) int[] arr = arr1 on the first call int[] arr = arr2 on the second call Arguments live; parameters die

9 REMEMBER THAT! Methods and Arguments The method does its job…
…with the arguments you gave it… it sorts the array you told it to sort it prints the line you told it to print it draws the fern in the place you told it to draw the fern …because that’s its job! REMEMBER THAT!

10 A Fern Drawing in a graphics window Has a root Has an angle
growing straight up Has a height height angle root

11 The drawFern Method A method to draw a fern
drawFern(double x, double y, double angle, double size) say where we want the bottom of the fern to be how many pixels across (x) and down (y) say what angle we want the fern drawn at straight up = 180º, flat out to right = 90º say how big we want the fern to be how many pixels from base to tip This method draws a fern – that’s its job!

12 Drawing the Fern Window is 800 across by 600 down angle = 180
full height of window (!) Window is 800 across by 600 down x,y = 400,600 angle = 180 size = 600 will be a bit shorter (room to grow) half way across all the way down straight up (180º)

13 Drawing Another Fern Window is 800 across by 600 down angle = 90
x,y = 200,300 angle = 90 size = 400 1/4 way across half width of window half way down off to side (90º)

14 Exercise: Draw this Fern
Window is 800 across by 600 down root is at centre of window angle is 120 degrees height is 40% of the window’s height

15 Compare these Ferns

16 One Fern is Part of the Other
In order to draw the big fern, we need to draw the little fern In fact, we need to draw three little ferns, all rooted at the same place, all the same size, but at different angles

17 Drawing the Fern Draw the stem Draw each of the three fronds
notice where it ends Draw each of the three fronds how to draw the fronds? we have a method that can do that! what’s it called? frond frond frond STEM

18 Drawing the Fern Draw the stem of the fern
end of the stem is the root of the fronds below Draw a smaller fern going up to the left Draw a smaller fern going straight up Draw a smaller fern going up to the right Stop drawing when the fern gets too small to see (say, 1 pixel tall)

19 Drawing Smaller Ferns Note where stem ended From that location
that’s the start of each small fern double[] end = drawStem(x, y, angle, size*0.5); From that location draw smaller fern at new angle… …40% of the original size drawFern(end[0], end[1], angle+60, size*0.4); drawFern(end[0], end[1], angle, size*0.4); drawFern(end[0], end[1], angle-60, size*0.4); We need to write this method. Returns new x,y in an array…. What about this method?

20 drawFern Function public void drawFern(double x, double y, double angle, double size) { double[] end; double length = size * 0.5; // stem is 50% the (nominal) height end = drawStem(x, y, angle, length); // returns x,y of stem end if (size > 1.0) { double smaller = size * 0.4; // smaller ferns 40% of full size drawFern(end[0], end[1], angle+60, smaller); drawFern(end[0], end[1], angle, smaller); drawFern(end[0], end[1], angle-60, smaller); } drawStem draws the stem, and says where it ended (so we can use that as the root of the other parts)

21 drawFern Function public void drawFern(double x, double y, double angle, double size) { double[] end; double length = size * 0.5; // stem is 50% the (nominal) height end = drawStem(x, y, angle, length); // returns x,y of stem end if (size > 1.0) { double smaller = size * 0.4; // smaller ferns 40% of full size drawFern(end[0], end[1], angle+60, smaller); drawFern(end[0], end[1], angle, smaller); drawFern(end[0], end[1], angle-60, smaller); } What does this function call do? It draws a fern! That’s its job! Different position, angle & size than the original….

22 Recursion A method that calls itself is said to be recursive
drawFern method calls itself drawFern is a recursive method Each call to the method does the job using the arguments it’s given! The computer does not get confused but you probably will!

23 Conditional Recursive Call
Recursive call is always conditional usually inside an if or else control Need some condition to stop the recursion otherwise you get a stack overflow error never stops calling itself drawFern recursive call is conditional on size if (size > 1.0) if size <= 1.0, recursion stops

24 Recursive Calls “Bottom out”
Draw 1 fern size 500… draws 3 ferns size 250… draws 9 ferns size 125… draws 27 ferns size 62.5… draws 81 ferns size 31.25… Each level is drawing smaller ferns eventually the ferns will be less than 1 pixel tall we’ll just draw the stems of those ferns

25 Fractals See the pretty pictures! These are “self-similar” objects
XaoS viewer you can download this for yourself These are “self-similar” objects smaller pieces of self look like whole thing like our fern

26 What is Recursion Recursion is a kind of “Divide & Conquer”
Divide problem into smaller problems Solve the smaller problems Recursion Divide problem into smaller versions of itself Smallest version(s) can be solved directly

27 Recursion in drawFern Problem of drawing large fern broken down into problem of drawing smaller ferns Smallest ferns too small to see draw the stem (a dot)… …but not the branches (no recursive calls)

28 Koch’s Snowflake Fractal image Draw a triangle, except… …on each side
draw a smaller triangle sticking out Keep going! see the animation on wikipedia

29 But WAIT! Each of those edges do the same thing!
A Snowflake Edge To draw an edge from x1,y1 to x2,y2: draw an edge to 1/3 the distance turn 60 degrees left draw an edge 1/3 of the original distance turn 120 degrees right But WAIT! Each of those edges do the same thing! And each of them too!

30 Recursion in the Snowflake
Problem of drawing an edge is broken down into problem of drawing smaller edges recursion! Smallest lines just get drawn straight one or two dots no recursion “base case”

31 Drawing the Snowflake Edge
Need to know how long the basic edge should be where to start (x, y) what direction to go in Return where we stop so we can start the next edge from there

32 Exercise show pseudo-code for this method
to drawEdge(x, y, angle, length): 1) 2)

33 Definitions and Recursion
Mathematicians like to define things Mathematicians like to define things recursively Recursive definition uses the thing being defined in its own definition! Step back: conditional definition

34 Conditional Definitions
Definition with two (or more) cases Math.abs(x) = x if x >= 0 –x otherwise Math.signum(x) = 1.0 if x > 0 0.0 if x == 0 -1.0 if x < 0

35 Recursive Definitions
One (or more) cases use the term being defined n! = 1 if n == 0 n*(n-1)! if n > 0 Fib(n) = 0 if n == 0 1 if n == 1 Fib(n–1)+Fib(n–2) if n > 1

36 Understanding Recursive Defns
How can you define something in terms of itself? Need a BASE CASE the small case that is defined directly there may be more than one Recursive case(s) must get “smaller” each case must be “closer” to some base case

37 Getting Smaller 4! = 4 * 3! Recursive Case 4 * 6 = 24
0! = 1 Base Case Base Case n! = 1 if n == 0 n*(n-1)! if n > 0 Recursive Case

38 Recursion in Factorial
Problem of finding factorial of a number broken down into problem of finding factorial of smaller number factorial of n is n times the factorial of n–1 factorial of 0 is 1

39 Recursive Function Definitions
public static int factorial( int n ) { if (n == 0) { // Base Case return 1; } else if (n > 0) { // Recursive Case return n * factorial(n-1); } else { throw new IllegalArgumentException(); } Base Case n! = 1 if n == 0 n*(n-1)! if n > 0 Recursive Case

40 Calling a Recursive Function
Just like calling any other function System.out.println( factorial(5) ); The function returns the factorial of what you give it because that’s what it does it returns the factorial every time you call it including when you call it inside its definition 120

41 Recursive Function Definitions
public static int factorial( int n ) { if (n == 0) // Base Case return 1; else // Recursive Case return n * factorial(n-1); } This will calculate the factorial of n–1 It’s what the factorial function does

42 Recursive Function Definitions
public void drawFern(double x, double y, double angle, double size) { double[] end; double length = size * 0.5; end = drawStem(x, y, angle, length); if (size > 1.0) { double smaller = size * 0.5; drawFern(end[0], end[1], angle+60, smaller); drawFern(end[0], end[1], angle, smaller); drawFern(end[0], end[1], angle-60, smaller); } This will draw a fern. It’s what the drawFern function does.

43 Exercise Write a recursive function to calculate the (non-negative integer) power of an integer Hint: it’ll look a LOT like the one for factorial nk = 1 if k == 0 n*nk-1 if k > 0

44 Thinking Recursively Need to recognize smaller versions of same problem, maybe slightly changed these ferns are like those ferns, but smaller and different place and angle if I had (n–1)! I could just multiply it by n And think of the really easy version a one pixel tall fern is just a dot 0! is just 1

45 Coding Recursively Remember the two imperatives: SMALLER! STOP!
when you call the method inside itself, one of the arguments has to be smaller than it was STOP! if the argument that gets smaller is very small (usually 0 or 1), then don’t do the recursion

46 Towers of Hanoi Buddhist monks in Hanoi
Set the task of moving golden disks (64) around diamond needles (3) all disks different sizes never put a bigger disk on a littler one When all 64 disks have been moved from the starting needle to the ending, the universe will end (In class demo – 4 disks)

47 What Would be Easy? What if there were only one disk? Start Peg
Extra Peg End Peg

48 A Little Less Easy What if there were two disks? Start Peg Extra Peg
1) Move one disk “out of the way” 2) Move other disk to the end post 3) Move first disk to the end post Start Peg Extra Peg End Peg

49 More Disks? Get top disks “out of the way” (takes MANY moves)
Start Peg (5) Extra Peg (5) End Peg (5) Start Peg (4) End Peg (4) Extra Peg(4)

50 Towers of Hanoi (5 disks)
Move bottom disk (one move) Start Peg (5) Extra Peg (5) End Peg (5)

51 Towers of Hanoi (5 disks)
Finish moving the top disks over to the end peg (MANY moves) Start Peg (5) Extra Peg (5) End Peg (5) Extra Peg (4) Start Peg (4) End Peg(4)

52 Towers of Hanoi (5 disks)
All done! Start Peg Extra Peg End Peg

53 Towers of Hanoi (Version 1)
If there’s only one disk move it to the end peg Else move the top disks out of the way extra peg becomes end peg for one less disks move the bottom disk to the end peg move the top disks onto the end peg start peg becomes extra peg

54 Towers of Hanoi (3 disks)
Move 3 disks here Move 2 disks out of the way Move 1 disk out of the way

55 Towers of Hanoi (3 disks)
Move 3 disks here Move 2 disks out of the way Move 1 disk here Move 1 disk out of the way

56 Towers of Hanoi (3 disks)
Move 3 disks here Move 2 disks out of the way Move other disk here Move 1 disk here

57 Towers of Hanoi (3 disks)
Move 3 disks here Move 2 disks out of the way Move 1 disk here Move other disk here

58 Towers of Hanoi (3 disks)
Move 3 disks here Move 2 disks here Move 1 disk here Move 1 disk out of the way

59 Towers of Hanoi (3 disks)
Move 3 disks here Move 2 disks here Move 1 disk out of the way Move 1 disk here

60 Towers of Hanoi (3 disks)
Move 3 disks here Move 2 disks here Move other disk here Move 1 disk here

61 Towers of Hanoi (3 disks)
Move 3 disks here All done! Move 2 disks here Move other disk here

62 Towers of Hanoi (Version 1)
public void hanoi(int numDisks, char start, char end, char extra) { if (numDisks == 1) { S.o.p(“Move a disk from ” + start + “ to ” + end); } else{ hanoi(numDisks – 1, start, extra, end); hanoi(numDisks – 1, extra, end, start); } stop smaller smaller

63 Towers of Hanoi (Version 1)
public void hanoi(int numDisks, char start, char end, char extra) { if (numDisks == 1) { S.o.p(“Move a disk from ” + start + “ to ” + end); } else{ hanoi(numDisks – 1, start, extra, end); hanoi(numDisks – 1, extra, end, start); }

64 What’s Easier than One Disk?
With no disks, there’d be nothing to do! with one disk: move zero disks out of the way move bottom disk to end peg mover zero disks onto bottom disk Exercise Towers of Hanoi (version 2) simplify the code from the previous slide

65 Recursion, Simplicity & Speed
Recursion generally makes code simpler less lines, so easier to grasp 4 lines for recursive towers of hanoi 30-40 lines for iterative (non-recursive) Sometimes it slows things down recursive fibonacci much slower than iterative Sometimes it speeds things up recursive sorting methods faster than iterative (generally!)

66 Recursive Sorting Method
Merge sort a pile of student papers if there’s more than one paper in this pile divide it into two equal(ish) piles merge-sort each smaller pile merge the results back together Much faster than inserting each paper into a sorted pile one at a time especially on a computer

67 But Some Things are Just Slow
Doesn’t matter how you do them, they take a long time Towers of Hanoi if it takes 1 second to move each disk each time how long until all 64 moved to the final peg? 1 hour? 1 day? 1 year? 100 years? a million years? n disks  2n – 1 steps 264 – 1 seconds… …about 585 billion years

68 Questions End of material for 1226 Final exam: Tuesday, April 19
7pm to 10pm Sobey Building 255 note CHANGE from original schedule! cumulative extra weight on material since 2nd midterm


Download ppt "Recursion Chapter 11."

Similar presentations


Ads by Google