CHAPTER 13 Recursion. Recursive Solution A recursive solution  solves a problem by solving a smaller instance of the problem. Example  How do we go.

Slides:



Advertisements
Similar presentations
Recursion Chapter 14. Overview Base case and general case of recursion. A recursion is a method that calls itself. That simplifies the problem. The simpler.
Advertisements

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter 13 – Recursion.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter 13 – Recursion.
Recursion - see Recursion. RHS – SOC 2 Recursion We know that: –We can define classes –We can define methods on classes –Mehtods can call other methods.
Chapter 18 Recursion "To iterate is human, to recurse divine.", L. Peter Deutsch.
Recursion. Binary search example postponed to end of lecture.
Unit 181 Recursion Definition Recursive Methods Example 1 How does Recursion work? Example 2 Problems with Recursion Infinite Recursion Exercises.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
Cis304 RECURSION. Recursion A recursive computation solves a problem by using the solution of the same problem with simpler input For recursion to terminate,
Chapter 2 Recursion: The Mirrors. © 2005 Pearson Addison-Wesley. All rights reserved2-2 Recursive Solutions Recursion is an extremely powerful problem-solving.
Recursion.
CHAPTER 17 RECURSION CHAPTER GOALS –To learn about the method of recursion –To understand the relationship between recursion and iteration –To analysis.
Recursion. Recursive Solutions Recursion breaks a problem into smaller identical problems – mirror images so to speak. By continuing to do this, eventually.
© 2006 Pearson Addison-Wesley. All rights reserved3-1 Chapter 3 Recursion: The Mirrors.
Recursion Chapter 7. Chapter 7: Recursion2 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn.
Chapter 2 Recursion: The Mirrors. © 2005 Pearson Addison-Wesley. All rights reserved2-2 Recursive Solutions Recursion is an extremely powerful problem-
CHAPTER 10 Recursion. 2 Recursive Thinking Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Recursion.
Chapter 14: Recursion Starting Out with C++ Early Objects
Recursion. Basic problem solving technique is to divide a problem into smaller subproblems These subproblems may also be divided into smaller subproblems.
Recursion. Basic problem solving technique is to divide a problem into smaller sub problems These sub problems may also be divided into smaller sub problems.
© 2006 Pearson Addison-Wesley. All rights reserved 3-1 Chapter 3 Recursion: The Mirrors.
Chapter 2 Recursion: The Mirrors. © 2005 Pearson Addison-Wesley. All rights reserved2-2 Recursive Solutions Recursion is an extremely powerful problem-
Chapter 3 Recursion: The Mirrors. © 2004 Pearson Addison-Wesley. All rights reserved 3-2 Recursive Solutions Recursion –An extremely powerful problem-solving.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 13 - Recursion.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 13 - Recursion.
Recursion Chapter 7. Chapter Objectives  To understand how to think recursively  To learn how to trace a recursive method  To learn how to write recursive.
Recursion A method is recursive if it makes a call to itself. A method is recursive if it makes a call to itself. For example: For example: public void.
Recursion l Powerful Tool l Useful in simplifying a problem (hides details of a problem) l The ability of a function to call itself l A recursive call.
Chapter 2 Recursion: The Mirrors. © 2005 Pearson Addison-Wesley. All rights reserved2-2 Recursive Solutions Recursion is an extremely powerful problem-
Recursion Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 2: Recursion: The Mirrors.
Data Structures & Algorithms CHAPTER 4 Searching Ms. Manal Al-Asmari.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 19 : Recursion King Fahd University of Petroleum & Minerals College of Computer.
AP Computer Science Instructor Alabama School of Fine Arts
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 2: Recursion: The Mirrors Data Abstraction & Problem Solving.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Thirteen: Recursion.
CHAPTER 17 RECURSION. CHAPTER GOALS To learn about the method of recursion To understand the relationship between recursion and iteration To analysis.
Chapter 18 Recursion. Chapter Goals To learn about the method of recursion To understand the relationship between recursion and iteration To analyze problems.
CSE 501N Fall ‘09 12: Recursion and Recursive Algorithms 8 October 2009 Nick Leidenfrost.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Recursive Solutions Recursion is an extremely powerful problem-solving.
Recursion. Math Review Given the following sequence: a 1 = 1 a n = 2*a n-1 OR a n+1 = 2*a n What are the values of the following? a 2 = a 3 = a 4 =
Data Structures R e c u r s i o n. Recursive Thinking Recursion is a problem-solving approach that can be used to generate simple solutions to certain.
Java Programming: Guided Learning with Early Objects Chapter 11 Recursion.
Copyright © 2013 by John Wiley & Sons. All rights reserved. RECURSION CHAPTER Slides by Rick Giles 13.
ICOM 4015: Advanced Programming Lecture 13 Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Reading: Chapter Thirteen:
Chapter 2 Recursion: The Mirrors. © 2005 Pearson Addison-Wesley. All rights reserved2-2 Recursive Solutions Recursion is an extremely powerful problem-solving.
1 Recursion n what is it? n how to build recursive algorithms n recursion analysis n tracing simple recursive functions n hands on attempts at writing.
Recursion Chapter 11. How it works “A recursive computation solves a problem by using the solution of the same problem with simpler inputs” Big Java,
1 Chapter 8 Recursion. 2 Objectives  To know what is a recursive function and the benefits of using recursive functions (§8.1).  To determine the base.
Programming With Java ICS201 University Of Ha’il1 Chapter 11 Recursion.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Recursion.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
Copyright © 2013 by John Wiley & Sons. All rights reserved. RECURSION CHAPTER 11 May 27, 2013 Slides by James Tam Department of Computer Science, University.
Chapter 2 Recursion: The Mirrors. © 2005 Pearson Addison-Wesley. All rights reserved2-2 Recursive Solutions Recursion is an extremely powerful problem-solving.
CSC 205 Programming II Lecture 8 Recursion.
Recursion - see Recursion
Recursion Version 1.0.
Chapter 13 Recursion.
Chapter 15 Recursion.
Chapter 13 – Recursion.
Recursion "To understand recursion, one must first understand recursion." -Stephen Hawking.
Recursion: The Mirrors
Recursion For some problems, it’s useful to have a method call itself.
Recursion - see Recursion
Advanced Java Programming
Chapter 13 – Recursion Big Java by Cay Horstmann
Recursion: The Mirrors
Chapter 3 :Recursion © 2011 Pearson Addison-Wesley. All rights reserved.
Recursion: The Mirrors
Presentation transcript:

CHAPTER 13 Recursion

Recursive Solution A recursive solution  solves a problem by solving a smaller instance of the problem. Example  How do we go about looking for a word in a dictionary?  Two methods  Sequential search  Binary search

3 Recursive Solutions Sequential search  Starts at the beginning of the collection  examine every element until a match is found  could be time consuming  what if the list contained millions of elements? Binary search  Repeatedly halves the collection and determines which half could contain the item  Uses a divide and conquer strategy

4 Dictionary Divide and conquer strategy First dividing the dictionary into two halves Chose the correct half Divide again into half (smaller problem) Continue until a base case is reached.  we have reached a single page containing the word.

//Search a dictionary for a word using a recursive binary search if (the dictionary contains only one page) { Scan the page for the word } else { Open the dictionary to a point near the middle. Determine which half of the dictionary contains the word. if (the word is in the first half of the dictionary) { Search the first half of the dictionary for the word. } else { Search the second half of the dictionary for the word. } //end if

6 Recursive Solutions Facts about a recursive solution  A recursive method calls itself  Each recursive call solves an identical, but smaller, problem  A test for the base case enables the recursive calls to stop  Base case: a known case in a recursive definition  Eventually, one of the smaller problems must be the base case

4 Question for Recursive Solutions 1. How can you define the problem in terms of a smaller identical problem? 2. Do you diminish the size of the problem? 3. What instance of the problem can serve as the base case? 4. As the problem size diminishes, will you reach this base case? 7

8 Recursive Solutions Theory - can solve a large variety of problems. In practice  computationally expensive  can only be used to solve small instances of such problems in a reasonable amount of time.

Triangle Problem Want to computer the area of the triangle Has a width n Each [] has area 1 [] [][] [][][] The third triangle number is 6.

Triangle Example Outline public class Triangle { public Triangle(int aWidth) { width = aWidth; } public int getArea() { ……. } private int width; }

Complete getArea() Take care of the case where the width is 1 or [] public int getArea() { if (width == 1) return 1; } Now that we know that we computer the area of the larger triangle as smallerArea + width;

Complete getArea() How do we get the smaller area? Make a smaller area and calculate. Triangle smallerTriangle = new Triangle(width -1) int smallerArea = samllerTriangle.getArea(); public int getArea() { if (width == 1) return 1; Triangle smallerTriangle = new Triangle(width -1) int smallerArea = samllerTriangle.getArea(); return smallerArea + width; }

Process The getArea method makes a smaller triangle of width 3. It calls getArea on that triangle. That method makes a smaller triangle of width 2. It calls getArea on that triangle. That method makes a smaller triangle of width 1. It calls the getArea on that triangle. That method returns 1. That method returns smallerArea + width = = 3. That method returns smallerArea + width = = 6. That method returns smallerArea + width =

14 A Recursive Method: The Factorial of n Problem  Compute the factorial of an integer n An iterative definition of factorial(n) factorial(n) = n * (n-1) * (n-2) * … * 1 for any integer n > 0 factorial(0) = 1

15 A Recursive Method: The Factorial of n A recursive definition of factorial(n) factorial(n) = 1if n = 0 n * factorial(n-1)if n > 0 A recurrence relation  A mathematical formula that generates the terms in a sequence from previous terms  Example factorial(n) = n * [(n-1) * (n-2) * … * 1] = n * factorial(n-1)

Factorial factorial(4) = 4*factorial(3) factorial(3) = 3*factorial(2) factorial(2) = 2*factorial(1) factorial(1) = 1*factorial(0) factorial(0) = 1 now we can solve it 16

Factorial factorial(0) = 1 factorial(1) = 1*factorial(0) = 1*1 = 1 factorial(2) = 2*factorial(1) = 2*1 = 2 factorial(3) = 3*factorial(2) = 3*2 = 6 factorial(4) = 4*factorial(3) = 4*6 = 24 17

Code 18 public class Factorial { public static void main(String [] arg) { fact(4); } public static int fact(int n) { if (n==0) return 1; else { int num = (n*fact(n-1)); System.out.println(num); return num; }

Permutations More complex example Write a class that lists all permutations of a string. How could we use such a class?  Password cracker  We have a given set of letters (all the alphabet)  We simple write a program that will allow us to get all permutations of that alphabet.  The larger the original set – the more permutations – the longer to crack

Permutations of “eat” Begin by removing the first letter. (e in this case) Generate all the combinations of the remaining letters  at and ta Therefore all the possible combinations of beginning with e are eat and eta Now get second letter (a in this case) Generate all the combinations of the remaining letters  et and te Repeat for each remaining letter

import java.util.ArrayList; public class PermutationGeneratorDemo { public static void main(String[] agrs) { PermutationGenerator generator = new PermutationGenerator("eat"); ArrayList permutations = generator.getPermutations(); for (String s: permutations) { System.out.println(s); } Permutation GeneratorDemo

PermutationGenerator public class PermutationGenerator { public PermutationGenerator(String aWord) { word = AWord; } public ArrayList getPermutations() { ArrayList result = new ArrayList (); // The empty string has a single permutations: iself if (word.length() == 0) { result.add(word); return result; }

PermutationGenerator // Loop through all character postions for (int i=0; i<word.length(); i++) { // Form a simpler work by removing the ith character String shorterWord = work.substring(0,i) + word.substring(i+1); //Generate all permutations of the simpler word PermutationGenerator shorterPermutationGenerator = new PermutationGenerator(shorterWord); ArrayList shorterWordPermutations = shorterPermutationGenerator.getPermutations();

PermutationGenerator // Add the removed charater to the front of // each permutation of the simpler word for String s: shorterWordPermutations) { result.add(word.charAt(i) + s); } return result; } private String word; }

Palindrome Test whether a string is equal to itself when you reverse all the characters.  Racecar Step 1: Consider ways to simplify inputs.  Remove first character  Remove last character  Remove a character from the middle  Cut the string into two halves.

Palindrome Step 2: See if the solutions you found in step 1, alone or in combination, work in solving your problem.  For palindrome try this  If the first and last characters are both letter, then check to see if they match. If so remove both and test again.  If the last character isn’t a letter, remove it and test the shorter string.  If the first character isn’t a letter, remove it and test the shorter string.

Palindrome Step 3: Find solutions to the simplest inputs.  Simplest strings  String with two characters  Strings with single character  The empty string Step 4: Implement the solution by combining the simple cases and the reduction step.

Code for IsPalindrome pubic 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));

Code for IsPalindrome // works only if both are letters) if ((Character.isLetter(first) && Character.isLetter(last)) { if (first==last) { // remove both first and last character. Sentence shorter = new Sentence(text.substring 1, length -1)); return shorter.isPalindrome(); } else return false; }

Code for IsPalindrome else if(! character.isLetter(last)) { Sentence shorter = new Sentence(text.substring(0, length -1)); return shoter.isPalindrome(); } else { Sentence shorter = new Sentence(text.substring(1)); return shorter.isPalindrome(); }

Helper Methods Assist by changing the original problem slightly Palindrome – create new sentence in every step Rather than testing whether the entire sentence is a palindrome, check whether a substring is a palindrome.

pubic boolean isPalindrome(int start, int end) { if (start >= end) return true; char first = Character.toLowerCase(text.charAt(start)); char last = Character.toLowerCase(text.charAt(end)); if (Character.isLetter(first) && Character.isLetter(last)) { if (first == last) { return isPalindrome(start +1, end -1) } else return false; } else if (!Charater.isLetter(last)) { return isPalindrome(start,end-1); } else { return isPalindrome(start+1, end) }

Method to Solve the Whole Problem public boolean isPalindrome() { return isPalindrome(0, text.length() -1) } Public sees this one. Work is performed by other one

Efficiency Occasionally runs much slower Most cases only slightly slower Easier to understand Easier to implement

Fibonacci Sequence Series of equations  Definitions  f 1 = 1  f 2 = 1  f n = f n-1 + f n-2

Code public class Recursive Fib { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter n: "); int n = in.nextInt(); for (int i = 1; k <=n; i++) { long f = fib(i); System.out.println("fib( " + i + ") = " + f); } public static long fib(int n) { if (n <=2) return 1: else return fib(n - 1) + fib(n - 2); }