recursion "to iterate is human, to recurse divine.", l. peter deutsch a+ ap computer...

Post on 31-Dec-2015

579 Views

Category:

Documents

1 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Recursion

"To iterate is human, to recurse divine.", L. Peter Deutsch

A+ AP Computer Science AReview Sessions

Session 2.2 Huntsville, AlabamaMarch 5, 2011

Carol Yarbrough

AP Computer Science InstructorAlabama School of Fine Arts

cyarbrough@asfa.k12.al.us

Recursion

• A recursive computation solves a problem by using the solution of the same problem with simpler values

• For recursion to terminate, there must be special cases for the simplest inputs.

Recursion

• Basic problem solving technique is to divide a problem into smaller subproblems

• These subproblems may also be divided into smaller subproblems

• When the subproblems are small enough to solve directly the process stops

• A recursive algorithm is a problem solution that has been expressed in terms of two or more easier to solve subproblems

Introduction to Java

Recursion Example – Solving Factorials

The problem of solving factorials is our first example of recursion. The factorial operation in mathematics is illustrated below.

1! = 12! = 2 * 1 or 2 * 1!3! = 3 * 2 * 1 or 3 * 2!4! = 4 * 3 * 2 *1 or 4 * 3!

Notice that each successive line can be solved in terms of the previous line. For example, 4! is equivalent to the problem

4 * 3!

Introduction to Java

Using A Recursive Method• A recursive method to solve the factorial problem is given below. Notice in the

last line of the method the recursive call. • The method calls another implementation of itself to solve a smaller version of

the problem.

int fact(int n)// returns the value of n!// precondition: n >= 1{ if (n == 1) return 1; else return n * fact(n - 1);}

The base case is a fundamental situation where no further problem solving is necessary.

In the case of finding factorials, the answer of 1! is by definition == 1. No further work is needed.

Introduction to Java

Recursion – Step By Step• Suppose we call the method to solve fact(4). • This will result in four calls of method fact.

fact(4): This is not the base case (n==1) so we return the result of 4 * fact(3). This multiplication will not be carried out until an answer is found for fact(3). This leads to the second call of fact to solve fact(3).

fact(3): Again, this is not the base case and we return 3 * fact (2). This leads to another recursive call to solve fact(2).

fact(2): Still, this is not the base case, we solve 2 * fact(1).

fact(1): Finally we reach the base case, which returns the value 1.

Introduction to Java

Recursion – Step By Step

• When a recursive call is made, the current computation is temporarily suspended and placed on the stack with all its current information available for later use.

• A completely new copy of the method is used to evaluate the recursive call. When that is completed, the value returned by the recursive call is used to complete the suspended computation. The suspended computation is removed from the stack and its work now proceeds.

• When the base case is encountered the recursion will now unwind and result in a final answer. The expressions below should be read from right to left.

fact(4) = 4 * fact(3) = 3 * fact(2) = 2 * fact(1) = 1

24 4 * 6 3 * 2 2 * 1

Introduction to Java

Recursion – The Picture

• Here is a picture. Look at what happens:

fact (4) 4 * fact (3)

fact (3) 3 * fact (2)

fact (2) 2 * fact (1)

fact (1)

1

2

6

fact (4) 24

• Each box represents a call of method fact. To solve fact(4) requires four calls of method fact.

• Notice that when the recursive calls were made inside the else statement, the value fed to the recursive call was (n-1). This is where the problem is getting smaller and simpler with the eventual goal of solving 1!.

Introduction to Java

Pitfalls Of Recursion

• If the recursion never reaches the base case, the recursive calls will continue until the computer runs out of memory and the program crashes. Experienced programmers try to examine the remains of a crash. The message “stack overflow error” or “heap storage exhaustion” indicates a possible runaway recursion.

• When programming recursively, you need to make sure that the algorithm is moving toward the base case. Each successive call of the algorithm must be solving a simpler version of the problem.

• Any recursive algorithm can be implemented iteratively, but sometimes only with great difficulty. However, a recursive solution will run more slowly than an iterative one because of the overhead of opening and closing the recursive calls.

Introduction to Java

Recursion – Example #2

int result = identity(10); System.out.println("The final answer is " + result);

public int identity(int num) { if (num < 1) return 10; else return num + identity(num - 2); }

The final answer is 40.

identity(num) returned value

identity (0) 10

identity (2) 12

identity (4) 16

identity (6) 22

identity (8) 30

identity (10) 40

Evaluating Exponents Recursively

static int power(int k, int n) {

// raise k to the power n if (n == 0) return 1; else return k * power(k, n – 1);}

Divide and Conquer

• Using this method each recursive subproblem is about one-half the size of the original problem

• If we could define power so that each subproblem was based on computing kn/2 instead of kn – 1 we could use the divide and conquer principle

• Recursive divide and conquer algorithms are often more efficient than iterative algorithms

Evaluating Exponents Using Divide and Conquer

static int power(int k, int n) { // raise k to the power n if (n == 0) return 1; else{ int t = power(k, n/2); if ((n % 2) == 0) return t * t; else return k * t * t;}

Thinking Recursively

• Problem: test whether a sentence is a palindrome

• Palindrome: a string that is equal to itself when you reverse all characters – A man, a plan, a canal–Panama! – Go hang a salami, I'm a lasagna hog – Madam, I'm Adam

public boolean isPalindrome() {int length = text.length();if( length <= 1 ) return true;char first = Character.toLowerCase(text.charAt(0));char last = Character.toLowerCase(text.charAt(length-1));if (Character.isLetter(first) && Character.isLetter(last)) {if( first == last ) {Sentence shorter = new Sentence(text.substring(1,length-1));return shorter.isPalindrome();}elsereturn false;}else if(!Character.isLetter(last)) {Sentence shorter = newSentence(text.substring(0,length-1));return shorter.isPalindrome();}else {// Remove first characterSentence shorter = new Sentence(text.substring(1));return shorter.isPalindrome();}}

Recursive Helper Methods• Sometimes it is easier to find a recursive solution

if you make a slight change to the original problem

• We will change the palindrome checker so you specify the start and end indices of the substring to check

• Rather than passing the entire substring as an argument

/**Test whether a substring of the sentence is a palindrome.@param start the index of the first character of the substring@param end the index of the last character of the substring@return true if the substring is a palindrome

*/public boolean isPalindromeHelper(int start int end)

This is what we call a recursive helper method.

• Start the recursion off by calling the main recursive function eg. isPalindrome().• The main recursive function doesn’t actuallycall itself. Instead, it just gets the recursion

started• It calls the helper function with initial

parameters eg. isPalindromeHelper(0, text.length() – 1)

• The helper function is recursive -- it calls itselfeg. isPalindromeHelper calls itself

The Efficiency of Recursion

• Recursive divide and conquer algorithms are often more efficient than iterative algorithms (binary searches, divide & conquer exponentiation )

• In many cases, a recursive solution is easier to understand and implement correctly than an iterative solution

• Often, however, recursive methods can be less efficient than their iterative counterparts

• Consider computing Fibonacci numbersfib(n) = fib(n-1) + fib(n-2)

Call Tree for Computing fib(6)

Figure 2:Call Tree of the Recursive fib method

See Jeliot animation of fib()

The Efficiency of Recursion

• Method takes so long because it computes the same values over and over

• The computation of fib(6) calls fib(3) three times

• Imitate the pencil-and-paper process to avoid computing the values more than once

The Efficiency of Recursion

• Occasionally, a recursive solution runs much slower than its iterative counterpart

• In most cases, the recursive solution is only slightly slower

• The iterative isPalindrome performs only slightly better than recursive solution – Each recursive method call takes a certain amount

of processor time

Using Mutual Recursions

• Problem: to compute the value of arithmetic expressions such as

• Computing expression is complicated – * and / bind more strongly than + and - – parentheses can be used to group subexpressions

3 + 4 * 5(3 + 4) * 51 - (2 - (3 - (4 - 5)))

Syntax Diagram for Evaluating an Expression

Figure 5:Syntax Diagrams for Evaluating an Expression

Using Mutual Recursions

• An expression can broken down into a sequence of terms, separated by + or -

• Each term is broken down into a sequence of factors, separated by * or /

• Each factor is either a parenthesized expression or a number

• The syntax trees represent which operations should be carried out first

Syntax Tree for Two Expressions

Figure 6:Syntax Trees for Two Expressions

Mutually Recursive Methods

• In a mutual recursion, a set of cooperating methods calls each other repeatedly

• To compute the value of an expression, implement 3 methods that call each other recursively – getExpressionValue – getTermValue – getFactorValue

Using Mutual Recursions

• To see the mutual recursion clearly, trace through the expression (3+4)*5:

• getExpressionValue calls getTermValue – getTermValue calls getFactorValue

• getFactorValue consumes the ( input • getFactorValue calls getExpressionValue

– getExpressionValue returns eventually with the value of 7, having consumed 3 + 4. This is the recursive call.

• getFactorValue consumes the ) input • getFactorValue returns 7

Continued

Using Mutual Recursions

– getTermValue consumes the inputs * and 5 and returns 35

• getExpressionValue returns 35

Tracing Recursive MethodsFunctional #1 public int f1(int n){ if (n == 0) return 0; return 5 + f1(n-1);} What is f1(3) ? What does f1 compute?

Functional #4 public int f4(int n){ if (n == 0 || n == 1) return 1; return f4(n-1) + f4(n-2);} What is f4(5) ? What does f4 compute? Draw the execution tree for

f4(5)? Why is f4 so inefficient?

String #1

public String s1(String s){ if (s.length() == 0) return ""; return s.substring(0, 1) + s1(s.substring(1));} What is s1("cat") ?

Arrays and ArrayLists #1

public int a1(int[] a, int n){ if (n == 0) return a[0]; int m = a1(a, n-1); if (m > a[n]) return m; else return a[n];}

What is a1(new int[]{4, 1, -3, 2}, 3) ?

Printing #1

public void p1(int n){ if (n > 1) { p1(n-1); System.out.print(n); p1(n-1); }} What does p1(4) print? What does p1(5) print?

39. Consider the following recursive method. public int recur(int n)

{ if (n <= 10) return n * 2;

else return recur(recur(n / 3));}What value is returned as a result of the call recur(27) ? (A) 8 (B) 9 (C) 12 (D) 16 (E)18

Recursive problems from APCS A 2008 Exam

40. Consider the following recursive method. public static void whatsItDo(String str)

{ int len = str.length();

if (len > 1) { String temp = str.substring(0, len - 1); whatsItDo(temp); System.out.println(temp);}} What is printed as a result of the call whatsItDo("WATCH")?(A) WATC WAT

WA W (B) WATCH

WATC WAT WA

(C) W WA WAT WATC (D) W WA WAT WATC WATCH

(E)WATCH WATC WAT WA W WA WAT WATC WATCH

13. Consider the following method. // Precondition: b > 0

public int surprise(int b) {

if ((b % 2) == 0) { if (b < 10)

return b; else

return ((b % 10) + surprise(b / 10));}else

{ if (b < 10)

return 0; else

return surprise(b / 10);}}

Which of the following expressions will evaluate to true?I. surprise(146781) == 0II. surprise(7754) == 4III. surprise(58216) == 16 (A) I only (B) II only (C) III only (D) II and III only (E) I, II, and III  

Recursive problems from APCS AB 2008 Exam

18. Consider the following method. public String recScramble(String str, int[] positions, int k)

{ if (str == null || str.length() == 0)

return ""; if (str.length() == 1)

return str; int pos = positions[k]; String nStr = str.substring(pos, pos + 1); str = str.substring(0, pos) + str.substring(pos + 1); return nStr + recScramble(str, positions, k + 1);

} Consider the following code segment. int[] indexes = {2, 1, 1}; System.out.println(recScramble("epic", indexes, 0)); What is printed as a result of executing the code segment? (A) cepi (B) epci (C) iecp (D) iepc (E) ipce

20. Consider the following method. public int addFun(int n)

{ if (n <= 0)

return 0; if (n == 1)

return 2; return addFun(n - 1) + addFun(n - 2);}What value is returned as a result of the call addFun(6) ?(A) 10(B) 12 (C) 16 (D) 26 (E) 32

To understand recursion, you must first understand

recursion.

top related