Factorial private int factorial (int n) { assert n >= 0; - - PowerPoint PPT Presentation

factorial
SMART_READER_LITE
LIVE PREVIEW

Factorial private int factorial (int n) { assert n >= 0; - - PowerPoint PPT Presentation

Factorial private int factorial (int n) { assert n >= 0; if (n == 0) { return 1; } return n * factorial(n-1); } factorial(3) => 3 * factorial(2) = 6 2 factorial(2)


slide-1
SLIDE 1

private int factorial (int n) { assert n >= 0; if (n == 0) { return 1; } return n * factorial(n-1); }

  • Factorial

factorial(3) => 3 * factorial(2) factorial(2) => 2 * factorial(1) factorial(1) => 1 * factorial(0) factorial(0) => 1 1 1 2 = 1 = 2 = 6

Recursive Thinking

Define the solution to a problem in terms of a solution to one or more “smaller” subproblems Define a base case, a subproblem that can be solved directly. 1 2 Tuesday, April 27, 2010

slide-2
SLIDE 2

Solution to recursive case Smaller subproblem Base case

private int factorial (int n) { assert n >= 0; if (n == 0) { return 1; } return n * factorial(n-1); }

  • Factorial

http:/ /imgs.xkcd.com/comics/ not_enough_work.png

Recursion Humor

3 4 Tuesday, April 27, 2010

slide-3
SLIDE 3

More Recursion Humor

http:/ / www.thinkgeek.com/ images/products/zoom/ b2ae_recursion.jpg

Recursive Structures

Define a data structure as a piece of data followed by a smaller data structure of the same type Define a base case, a trivial piece of data with nothing following it. 5 6 Tuesday, April 27, 2010

slide-4
SLIDE 4

Drawing with the Mouse Drawing with the Mouse

Lots of short lines! Call one group of connected lines a “scribble”

7 8 Tuesday, April 27, 2010

slide-5
SLIDE 5

What is a Scribble?

A line segment, followed by A shorter Scribble Base case: an “empty” scribble

Scribble Hierarchy

<<interface>> Scribble Empty Scribble Recursive Scribble

9 10 Tuesday, April 27, 2010

slide-6
SLIDE 6

RecursiveScribble

public class RecursiveScribble implements Scribble { / / This line private Line2D line; private Color color; / / The lines that follow it private Scribble rest; / / Methods ... }

EmptyScribble

public class EmptyScribble implements Scribble { / / No instance variables!! / / Methods ... }

11 12 Tuesday, April 27, 2010

slide-7
SLIDE 7

Changing the Color of a Scribble

in RecursiveScribble: public void setColor (Color newColor) { / / Change the color of this line color = newColor; / / Recursively change the rest of the scribble rest.setColor (newColor); } in EmptyScribble: public void setColor (Color newColor) { / / Nothing to do! }

Broccoli

13 14 Tuesday, April 27, 2010

slide-8
SLIDE 8

Broccoli

Smaller substructure => 3 More pieces of broccoli Base case => Flower Little data => Stem

Towers of Hanoi

End of the world in 585 billion years! http:/ / en.wikipedia.org/wiki/Tower_of_Hanoi

15 16 Tuesday, April 27, 2010