+ All Categories
Home > Documents > 2002-2009 Prentice Hall. All rights reserved. 1 Recursion (Section 7.13 & Exercise7.40 from ed.3)...

2002-2009 Prentice Hall. All rights reserved. 1 Recursion (Section 7.13 & Exercise7.40 from ed.3)...

Date post: 14-Dec-2015
Category:
Upload: ezra-atkinson
View: 213 times
Download: 0 times
Share this document with a friend
20
2002-2009 Prentice Hall. All rights reserved. 1 Recursion (Section 7.13 & Exercise7.40 from ed.3) (Sections 6.15, 6.16 from ed.1) Many slides modified by Prof. L. Lilien (even many without an explicit message). Slides added by L.Lilien are © 2006-2009 Leszek T. Lilien. Permision to use for non-commercial purposes slides added by L.Lilien’s will be gladly granted upon a written (e.g., emailed) request.
Transcript
Page 1: 2002-2009 Prentice Hall. All rights reserved. 1 Recursion (Section 7.13 & Exercise7.40 from ed.3) (Sections 6.15, 6.16 from ed.1) Many slides modified.

2002-2009 Prentice Hall. All rights reserved.

1

Recursion(Section 7.13 & Exercise7.40 from ed.3)

(Sections 6.15, 6.16 from ed.1)

Many slides modified by Prof. L. Lilien (even many without an explicit message).

Slides added by L.Lilien are © 2006-2009 Leszek T. Lilien.

Permision to use for non-commercial purposes slides added by L.Lilien’s will be gladly granted upon a written (e.g., emailed) request.

Page 2: 2002-2009 Prentice Hall. All rights reserved. 1 Recursion (Section 7.13 & Exercise7.40 from ed.3) (Sections 6.15, 6.16 from ed.1) Many slides modified.

2002-2009 Prentice Hall. All rights reserved.

2

7.13. Recursion• Recursive methods - call themselves:

– Directly

– Indirectly

• Call others methods which call it

• Continually breaks problem down to simpler forms– Each method call divides the problem into two pieces:

• A piece that the method knows how to do

• A recursive call (a.k.a. recursion step) that solves a smaller problem

• In other words, each recursive method:– Waits till recursive call made by it finishes

– Then finishes itself

• The method must converge in order to end recursion– Must include a “terminating condition” (see below)

Page 3: 2002-2009 Prentice Hall. All rights reserved. 1 Recursion (Section 7.13 & Exercise7.40 from ed.3) (Sections 6.15, 6.16 from ed.1) Many slides modified.

2002-2009 Prentice Hall. All rights reserved.

37.13.  Recursion (Cont.)

Fig. 7.16 | Recursive evaluation of 5!

Recursive Example 1: Factorial Calculation

• Recursive formula for factorial calculation:

n! = n . (n – 1)! Termination conditions: 1! = 1 0! = 1

Page 4: 2002-2009 Prentice Hall. All rights reserved. 1 Recursion (Section 7.13 & Exercise7.40 from ed.3) (Sections 6.15, 6.16 from ed.1) Many slides modified.

2002-2009 Prentice Hall. All rights reserved.

4 1 // Fig. 7.17: FactorialTest.cs

2 // Recursive Factorial method.

3 using System;

4

5 public class FactorialTest

6 {

7 public static void Main( string[] args )

8 {

9 // calculate the factorials of 0 through 10

10 for ( long counter = 0; counter <= 10; counter++ )

11 Console.WriteLine( "{0}! = {1}",

12 counter, Factorial( counter ) );

13 } // end Main

14

15 // recursive declaration of method Factorial

Outline

FactorialTest.cs

16 public static long Factorial( long number )

17 {

18 // base case

19 if ( number <= 1 )

20 return 1;

21 // recursion step

22 else

23 return number * Factorial( number - 1 );

24 } // end method Factorial

25 } // end class FactorialTest

0! = 1 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720 7! = 5040 8! = 40320 9! = 362880 10! = 3628800

Program output:

First, test to determine whether the terminating condition is true.

The recursive call solves a slightly simpler problem (“number -1” vs. “number”) than the original calculation.

Page 5: 2002-2009 Prentice Hall. All rights reserved. 1 Recursion (Section 7.13 & Exercise7.40 from ed.3) (Sections 6.15, 6.16 from ed.1) Many slides modified.

2002-2009 Prentice Hall. All rights reserved.

5

• Run FactorialTest and watch Call Stack (code for FactorialTest is on the course web page)

- Set up/open Call Stack window as follows:1) set up a breakpoint at Line 11:

Console.WriteLine("{0}! = {1}", 2) select Debug>>Start Debugging 3) if Call Stack window does not show up, select Debug>>Windows>> Call Stack 4) Use F11 (or Debug>>Step Into) to execute step-by-step

© Leszek T. Lilien, 2009

Page 6: 2002-2009 Prentice Hall. All rights reserved. 1 Recursion (Section 7.13 & Exercise7.40 from ed.3) (Sections 6.15, 6.16 from ed.1) Many slides modified.

2002-2009 Prentice Hall. All rights reserved.

6

** READ LATER** 7.13.  Recursion (Cont.)

Common Programming Error 7.11

Infinite recursion (error!) occurs when the programmer either:

1)omits the base case (terminating condition), or

2)writes the recursion step incorrectly so that it does not converge on the base case

Infinite recursion will eventually exhaust available memory.

This error is analogous to the problem of an infinite loop in an iterative (nonrecursive) solution.

Page 7: 2002-2009 Prentice Hall. All rights reserved. 1 Recursion (Section 7.13 & Exercise7.40 from ed.3) (Sections 6.15, 6.16 from ed.1) Many slides modified.

2002-2009 Prentice Hall. All rights reserved.

7[from textbook edition 1]

6.15. Recursion Example 1: The Fibonacci Sequence

• Fibonacci Sequence– Recursion used to calculate F(n):

• F(0) = 0

• F(1) = 1

• F(n) = F(n - 1) + F(n - 2)

• Example – – Set of recursive calls

to method Fibonacci [from Fig. 6.17 (ed.1)]

return 1 return 0

F( 1 ) F( 0 ) return 1

F( 3 )

F( 2 ) F( 1 )+return

return +

Two terminating conditions.}

Page 8: 2002-2009 Prentice Hall. All rights reserved. 1 Recursion (Section 7.13 & Exercise7.40 from ed.3) (Sections 6.15, 6.16 from ed.1) Many slides modified.

2002-2009 Prentice Hall. All rights reserved.

8

// FibonacciTest.cs [cf. ed.1-Fig. 6.16 (a Windows Forms application)]// Recursive Fibonacci method (uses Console application).

using System;

public class FibonacciTest{ public static void Main(string[] args) { // Ask user to input an input number for calculations Console.Write("Enter an integer ( 1-25 ): "); int inputNumber = Convert.ToInt32(Console.ReadLine());

// Calculate Fibonacci number for the input number long fibonacciNumber = Fibonacci(inputNumber);

// Output the Fibonacci number for the input number Console.WriteLine("Fibonacci({0}) = {1}", inputNumber, fibonacciNumber); }

// Calculates Fibonacci number. // Static method, so can be called without first creating a // new instance of the FibonacciTest class (to which the method belongs). public static long Fibonacci(int number) { if (number == 0 || number == 1) return number; // Fibonacci(0)=0 and Fibonacci(1)=1 else return Fibonacci(number - 1) + Fibonacci(number - 2); } // end method Fibonacci} // end class FibonacciTest

© Leszek T. Lilien, 2009

Main calls the Fibonacci method to get result

The recursion ends when the number is 0 or 1

Fibonacci calls itself twice, to get the result as the sum of the two previous Fibonacci numbers

Page 9: 2002-2009 Prentice Hall. All rights reserved. 1 Recursion (Section 7.13 & Exercise7.40 from ed.3) (Sections 6.15, 6.16 from ed.1) Many slides modified.

2002-2009 Prentice Hall. All rights reserved.

9

Output example 1:Enter an integer ( 1-25 ): 3Fibonacci(3) = 2

Output example 2:Enter an integer ( 1-25 ): 22Fibonacci(22) = 17711

© Leszek T. Lilien, 2009

Page 10: 2002-2009 Prentice Hall. All rights reserved. 1 Recursion (Section 7.13 & Exercise7.40 from ed.3) (Sections 6.15, 6.16 from ed.1) Many slides modified.

2002-2009 Prentice Hall. All rights reserved.

10

• Run FibonacciTest and watch Call Stack (copy code for FibonacciTest from page “-2” or from the course web page)

- Set up/use Call Stack window as follows:1) set up a breakpoint at Line 15:

long fibonacciNumber = Fibonacci(inputNumber); 2) select Debug>>Start Debugging 3) if Call Stack window does not show up, select Debug>>Windows>> Call Stack 4) Use F11 (or Debug>>Step Into) to execute step-by-step

© Leszek T. Lilien, 2009

Page 11: 2002-2009 Prentice Hall. All rights reserved. 1 Recursion (Section 7.13 & Exercise7.40 from ed.3) (Sections 6.15, 6.16 from ed.1) Many slides modified.

2002-2009 Prentice Hall. All rights reserved.

11

[from textbook edition 1]

6.16. Recursion vs. Iteration

• Iteration– Uses repetition structures

• while, do/while, for, foreach

– Continues until counter fails repetition condition

• Recursion– Uses selection structures

• if, if/else, switch

– Repetition through method calls– Continues until a termination case reached (e.g., F(0) or F(1) for

Fibonacci)

– Creates duplicates of the variables• Can consume a lot of memory and processor speed

Page 12: 2002-2009 Prentice Hall. All rights reserved. 1 Recursion (Section 7.13 & Exercise7.40 from ed.3) (Sections 6.15, 6.16 from ed.1) Many slides modified.

2002-2009 Prentice Hall. All rights reserved.

12Exercise 7.40. (p.330-ed.3)  Recursion Example 3: Towers of Hanoi

• Background:– In a temple in the Far East, priests are attempting to move a stack of 64

disks from one peg to another– The legend: The world will end when

the priests complete their task

– The initial stack of 64 disks is threaded onto Peg 1 and arranged from bottom to top by decreasing size

– The priests are attempting to move the stack from this peg to Peg 3 under the constraints that:

• Exactly one disk is moved at a time and • At no time may a larger disk be placed above a smaller disk

– Peg 2 is available for temporarily holding disks

Page 13: 2002-2009 Prentice Hall. All rights reserved. 1 Recursion (Section 7.13 & Exercise7.40 from ed.3) (Sections 6.15, 6.16 from ed.1) Many slides modified.

2002-2009 Prentice Hall. All rights reserved.

13Towers of Hanoi – Cont.

• Write an application to solve the Towers of Hanoi problem.• Allow the user to enter the number of disks.• Use a recursive Tower method with four parameters:

a) the number of disks to be moved,b) the id of the initial peg (on which these disks are initially threaded),c) the id of the final peg (to which this stack of disks is to be moved), d) the id of the temporary peg (to be used as a temporary holding area).

• The application should display the precise instructions it will take to move the disks from the starting peg to the destination peg. — Example: To move a stack of 3 disks from Peg 1 to Peg 3, the

application should display the following series of moves:1 --> 3 (This notation means “Move the top disk from Peg 1 to Peg 3.”)1 --> 23 --> 21 --> 32 --> 12 --> 31 --> 3

Page 14: 2002-2009 Prentice Hall. All rights reserved. 1 Recursion (Section 7.13 & Exercise7.40 from ed.3) (Sections 6.15, 6.16 from ed.1) Many slides modified.

2002-2009 Prentice Hall. All rights reserved.

14Towers of Hanoi – Cont.

• Developing an algorithm that displays the precise sequence of peg-to-peg disk transfers• If we were to approach this problem with conventional methods (e.g.

using iteration), we would rapidly find ourselves hopelessly knotted up in managing the disks

• If we attack the problem with recursion in mind, it immediately becomes quite easy to solve

Page 15: 2002-2009 Prentice Hall. All rights reserved. 1 Recursion (Section 7.13 & Exercise7.40 from ed.3) (Sections 6.15, 6.16 from ed.1) Many slides modified.

2002-2009 Prentice Hall. All rights reserved.

15Towers of Hanoi – Cont.

• Design -- Approach:

1) Moving n disks can be viewed recursively in terms of moving only n – 1 disks:a) Move n – 1 disks from Peg 1 to Peg 2, using Peg 3 as a

temporary holding areab) Move the last disk (the largest) from Peg 1 to Peg 3c) Move the n – 1 disks from Peg 2 to Peg 3, using Peg 1 as a

temporary holding area

2) Terminating condition (base case ): The process ends when the last task requires moving n = 1 disks

This last task is accomplished by simply moving the disk (from the initial to the final peg) without the need for a temporary holding area

Page 16: 2002-2009 Prentice Hall. All rights reserved. 1 Recursion (Section 7.13 & Exercise7.40 from ed.3) (Sections 6.15, 6.16 from ed.1) Many slides modified.

2002-2009 Prentice Hall. All rights reserved.

16

Towers of Hanoi – Cont.

1 // Exercise 7.40 Solution: TowerOfHanoi.cs

2 // Application solves the towers of Hanoi problem, and

3 // demonstrates recursion

4 using System;

5

6 public class TowerOfHanoi

7 {

8 public static void Main( string[] args )

9 {

10 int disks; // number of disks in the tower

11

12 // prompt user for number of disks and read value

13 Console.Write( "Enter number of disks ( 1-9 ): " );

14 disks = Convert.ToInt32( Console.ReadLine() );

15 16 // actually sort the number of disks specified by user

17 Tower( disks, 1, 3, 2 ); // Move fr. peg “1” to peg “3” (using peg “2”)

18 } // end Main

19

20 // recursively move disks through towers=pegs (fr. peg 1 to peg3 using peg2)

21 public static void Tower( int disks, int peg1, int peg3, int peg2 )

22 {

23 if ( disks == 1 )

24 {

25 Console.WriteLine( "{0} --> {1}", peg1, peg3 );

26 return;

27 }

28

29 // move ( disks - 1 ) disks from peg1 to peg2 recursively

30 Tower( disks - 1, peg1, peg2, peg3 ); // fr. peg “1” to peg “2 (!)

31

32 // move last disk from peg1 to peg3 (base case)

33 Console.WriteLine( "{0} --> {1}", peg1, peg3 );

34

35 // move ( disks - 1 ) disks from peg2 to peg3 recursively

36 Tower( disks - 1, peg2, peg3, peg1 ); // fr. peg “2 to peg “3

37 } // end method Tower

38 } // end class TowerOfHanoi

Page 17: 2002-2009 Prentice Hall. All rights reserved. 1 Recursion (Section 7.13 & Exercise7.40 from ed.3) (Sections 6.15, 6.16 from ed.1) Many slides modified.

2002-2009 Prentice Hall. All rights reserved.

17Towers of Hanoi – Cont.

• Note: Don’t try to run the following program for values larger than 9 – you will use a lot of time and display (or printout) space.• We’ll learn later how complexity theory explains this

Page 18: 2002-2009 Prentice Hall. All rights reserved. 1 Recursion (Section 7.13 & Exercise7.40 from ed.3) (Sections 6.15, 6.16 from ed.1) Many slides modified.

2002-2009 Prentice Hall. All rights reserved.

18

Towers of Hanoi – Cont.

Output for number of disks = 3: Enter number of disks ( 1-9 ): 31 --> 31 --> 23 --> 21 --> 32 --> 12 --> 31 --> 3

Page 19: 2002-2009 Prentice Hall. All rights reserved. 1 Recursion (Section 7.13 & Exercise7.40 from ed.3) (Sections 6.15, 6.16 from ed.1) Many slides modified.

2002-2009 Prentice Hall. All rights reserved.

19

Towers of Hanoi – Cont.

Output for number of disks = 4: Enter number of disks ( 1-9 ): 41 --> 21 --> 32 --> 31 --> 23 --> 13 --> 21 --> 21 --> 32 --> 32 --> 13 --> 12 --> 31 --> 21 --> 32 --> 3

Page 20: 2002-2009 Prentice Hall. All rights reserved. 1 Recursion (Section 7.13 & Exercise7.40 from ed.3) (Sections 6.15, 6.16 from ed.1) Many slides modified.

2002-2009 Prentice Hall. All rights reserved.

20

The End


Recommended