Recursion -- Introduction

Slides:



Advertisements
Similar presentations
© 2006 Pearson Education Chapter 8: Recursion Presentation slides for Java Software Solutions for AP* Computer Science A 2nd Edition by John Lewis, William.
Advertisements

Chapter 17 Recursion.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 7: Recursion Java Software Structures: Designing and Using.
Chapter 8: Recursion Java Software Solutions
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Recursion. Recursive Definitions A recursive definition is one which uses the word being defined in the definition Not always useful:  for example, in.
CISH 4960 Introduction to Programming Lecture 101 Introduction to Programming Lecture 10 Recursion/Data Structures Tom Blough
Swap I class Swap { public static void swap(int i, int j) {
Scott Grissom, copyright 2004 Chapter 5 Slide 1 Analysis of Algorithms (Ch 5) Chapter 5 focuses on: algorithm analysis searching algorithms sorting algorithms.
1 Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  Chapter 11 of the book.
1 Introduction to Recursion  Introduction to Recursion  Example 1: Factorial  Example 2: Reversing Strings  Example 3: Fibonacci  Infinite Recursion.
Chapter 10 Recursion. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Explain the underlying concepts of recursion.
Chapter Day 25. © 2007 Pearson Addison-Wesley. All rights reserved Agenda Day 25 Problem set 5 Posted (Last one)  Due Dec 8 Capstones Schedule  3rd.
ELC 310 Day 24. © 2004 Pearson Addison-Wesley. All rights reserved11-2 Agenda Questions? Problem set 5 Parts A Corrected  Good results Problem set 5.
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.
Chapter 11 Recursion. © 2004 Pearson Addison-Wesley. All rights reserved11-2 Recursion Recursion is a fundamental programming technique that can provide.
Recursion Chapter 5.
© 2004 Pearson Addison-Wesley. All rights reserved October 27, 2006 Recursion (part 2) ComS 207: Programming I (in Java) Iowa State University, FALL 2006.
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved11-2 Arrays Arrays are objects that help us organize large amounts of information.
CHAPTER 02 Recursion Compiled by: Dr. Mohammad Omar Alhawarat.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 19 : Recursion King Fahd University of Petroleum & Minerals College of Computer.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Chapter 8 Recursion Modified.
Chapter 4 Recursion. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Explain the underlying concepts of recursion.
Chapter 5 Loops.
1Recursion  Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems  We will focus on: thinking.
CSE 501N Fall ‘09 12: Recursion and Recursive Algorithms 8 October 2009 Nick Leidenfrost.
11-1 Recursive Thinking A recursive definition is one which uses the word or concept being defined in the definition itself When defining an English word,
Lecture 7 b Recursion is a fundamental programming technique that can provide an elegant solution to certain kinds of problems b Today: thinking in a recursive.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 8: Recursion Presentation slides for Java Software Solutions for AP* Computer Science 3rd.
1 Recursion Recursion is a powerful programming technique that provides elegant solutions to certain problems. Chapter 11 focuses on explaining the underlying.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12 Recursion.
Recursion A recursive definition is one which uses the word or concept being defined in the definition itself Example: “A computer is a machine.
Recursion Chapter 17 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
COS 312 DAY 24 Tony Gauvin. Ch 1 -2 Agenda Questions? Assignment 6 Corrected Assignment 7 (bonus) – Due May 11 – Will be scored on 15 point scale, points.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Recursion Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems © 2004 Pearson Addison-Wesley.
CHAPTER 4: Linked Structures
Chapter 12 Recursion.
CprE 185: Intro to Problem Solving (using C)
Abdulmotaleb El Saddik University of Ottawa
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Chapter 8: Recursion Java Software Solutions
Java Software Structures: John Lewis & Joseph Chase
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Java Software Solutions Foundations of Program Design 9th Edition
Recursive Definitions
Chapter 12 Recursion (methods calling themselves)
Recursion Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems We will focus on: thinking in.
Recursion (part 2) October 26, 2007 ComS 207: Programming I (in Java)
Java Software Solutions Foundations of Program Design Seventh Edition
Chapter 8: Recursion Java Software Solutions
Chapter 8 Recursion.
Recursion (part 1) October 24, 2007 ComS 207: Programming I (in Java)
Unit 3 Test: Friday.
Chapter 11 Recursion.
Chapter 8: Recursion Java Software Solutions
11 Recursion Software Solutions Lewis & Loftus java 5TH EDITION
Recursion (part 2) March 22, 2006 ComS 207: Programming I (in Java)
Outline Boolean Expressions The if Statement Comparing Data
Java Software Solutions Foundations of Program Design Sixth Edition
Recursive Thinking.
Recursion (part 1) October 25, 2006 ComS 207: Programming I (in Java)
Presentation transcript:

Recursion -- Introduction Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems Chapter 12 focuses on: thinking in a recursive manner programming in a recursive manner the correct use of recursion recursion examples Chapter 12 Copyright 1997 by John Lewis and William Loftus. All rights reserved.

Copyright 1997 by John Lewis and William Loftus. All rights reserved. Recursive Thinking A recursive definition is one which uses the word or concept being defined in the definition itself A recursive definition can be an appropriate way to express a concept Before applying recursion to programming, it is best to practice thinking recursively Chapter 12 Copyright 1997 by John Lewis and William Loftus. All rights reserved.

Recursive Definitions Consider the following list of numbers: 24, 88, 40, 37 Such a list can be defined as A LIST is a: number or a: number comma LIST That is, a LIST is defined to be a single number, or a number followed by a comma followed by a LIST The concept of a LIST is used to define itself Chapter 12 Copyright 1997 by John Lewis and William Loftus. All rights reserved.

Recursive Definitions The recursive part of the LIST definition is used several times, terminating with the non-recursive part: number comma LIST 24 , 88, 40, 37 88 , 40, 37 40 , 37 number 37 Chapter 12 Copyright 1997 by John Lewis and William Loftus. All rights reserved.

Copyright 1997 by John Lewis and William Loftus. All rights reserved. Infinite Recursion All recursive definitions have to have a non-recursive part If they didn't, there would be no way to terminate the recursive path Such a definition would cause infinite recursion This problem is similar to an infinite loop, but the non-terminating "loop" is part of the definition itself The non-recursive part is often called the base case Chapter 12 Copyright 1997 by John Lewis and William Loftus. All rights reserved.

Recursive Definitions N!, for any positive integer N, is defined to be the product of all integers between 1 and N inclusive This definition can be expressed recursively as: 1! = 1 N! = N * (N-1)! The concept of the factorial is defined in terms of another factorial Eventually, the base case of 1! is reached Chapter 12 Copyright 1997 by John Lewis and William Loftus. All rights reserved.

Recursive Definitions 5! 5 * 4! 4 * 3! 3 * 2! 2 * 1! 1 120 24 6 2 Chapter 12 Copyright 1997 by John Lewis and William Loftus. All rights reserved.

Recursive Programming A method in Java can invoke itself; if set up that way, it is called a recursive method The code of a recursive method must be structured to handle both the base case and the recursive case Each call to the method sets up a new execution environment, with new parameters and local variables As always, when the method completes, control returns to the method that invoked it (which may be an earlier invocation of itself) Chapter 12 Copyright 1997 by John Lewis and William Loftus. All rights reserved.

Recursive Programming Consider the problem of computing the sum of all the numbers between 1 and any positive integer N This problem can be recursively defined as: See Recursive_Sum.java i = 1 N N-1 N-2 = N + = N + (N-1) + = etc. Chapter 12 Copyright 1997 by John Lewis and William Loftus. All rights reserved.

Example: Recursive_Sum.java class Recursive_Sum { public static void main (String[] args) { System.out.println ("The sum of 1 to 3 is " + sum (3)); System.out.println ("The sum of 1 to 6 is " + sum (6)); System.out.println ("The sum of 1 to 10 is " + sum (10)); System.out.println ("The sum of 1 to 15 is " + sum (15)); } // method main public static int sum (int N) { int result; if (N == 1) result = 1; else result = N + sum (N-1); return result; } // method sum } // class Recursive_Sum Chapter 12 Copyright 1997 by John Lewis and William Loftus. All rights reserved.

Recursive Programming main sum sum(3) sum(1) sum(2) result = 1 result = 3 result = 6 Chapter 12 Copyright 1997 by John Lewis and William Loftus. All rights reserved.

Recursive Programming Note that just because we can use recursion to solve a problem, doesn't mean we should For instance, we usually would not use recursion to solve the sum of 1 to N problem, because the iterative version is easier to understand However, for some problems, recursion provides an elegant solution, often cleaner than an iterative version You must carefully decide whether recursion is the correct technique for any problem Chapter 12 Copyright 1997 by John Lewis and William Loftus. All rights reserved.

Copyright 1997 by John Lewis and William Loftus. All rights reserved. Indirect Recursion A method invoking itself is considered to be direct recursion A method could invoke another method, which invokes another, etc., until eventually the original method is invoked again For example, method m1 could invoke m2, which invokes m3, which in turn invokes m1 again This is called indirect recursion, and requires all the same care as direct recursion It is often more difficult to trace and debug Chapter 12 Copyright 1997 by John Lewis and William Loftus. All rights reserved.

Copyright 1997 by John Lewis and William Loftus. All rights reserved. Indirect Recursion m1 m2 m3 m1 m2 m3 m1 m2 m3 Chapter 12 Copyright 1997 by John Lewis and William Loftus. All rights reserved.

Copyright 1997 by John Lewis and William Loftus. All rights reserved. Using Recursion Recursion is best served when it is easy to define a smaller subset of the problem in terms of the original Consider the task of repeatedly displaying a set of images in a mosaic that is reminiscent of looking in two mirrors reflecting each other The base case is reached when the area for the images shrinks to a certain size See Repeating_Pictures.java Chapter 12 Copyright 1997 by John Lewis and William Loftus. All rights reserved.

Example: Repeating_Pictures import java.applet.Applet; import java.awt.*; public class Repeating_Pictures extends Applet { private final int SIZE = 300; // Size of applet private final int STOP = 20; // Smallest picture size private final int OFFSET = 2; // Picture offset from lines private Image world; private Image everest; private Image goat; public void init() { world = getImage (getDocumentBase(), "world.gif"); everest = getImage (getDocumentBase(), "everest.gif"); goat = getImage (getDocumentBase(), "goat.gif"); setSize (SIZE, SIZE); } // method init Chapter 12 Copyright 1997 by John Lewis and William Loftus. All rights reserved.

Copyright 1997 by John Lewis and William Loftus. All rights reserved. // Draws the entire picture recursively. public void draw_pictures (int size, Graphics page) { // Draw lines to create four quadrants page.drawLine (size/2, 0, size/2, size); // vertical page.drawLine (0, size/2, size, size/2); // horizontal // Draw three images in different quadrants page.drawImage (world, 0+OFFSET, size/2+OFFSET, size/2-(OFFSET*2), size/2-(OFFSET*2), this); page.drawImage (everest, size/2+OFFSET, 0+OFFSET, page.drawImage (goat, size/2+OFFSET, size/2+OFFSET, // Draw the entire picture again in the first quadrant if (size > STOP) draw_pictures (size/2, page); } // method draw_pictures // Performs the initial call to the draw_pictures method. public void paint (Graphics page) { draw_pictures (getSize().width, page); } // method paint } // class Repeating_Pictures Chapter 12 Copyright 1997 by John Lewis and William Loftus. All rights reserved.

Copyright 1997 by John Lewis and William Loftus. All rights reserved. Using Recursion A palindrome is a string of characters that reads the same forward and backward: radar able was I ere I saw elba To determine whether a string is a palindrome, you can examine the two outer characters, and work your way in toward the middle of the string This solution is easily defined recursively See Palindromes.java Chapter 12 Copyright 1997 by John Lewis and William Loftus. All rights reserved.

Example: Palindromes.java public class Palindromes { // Creates a Palindrome_Tester object, and tests several strings. public static void main (String[] args) { Palindrome_Tester tester = new Palindrome_Tester(); System.out.println ("radar is a palindrome? " + tester.ptest ("radar")); System.out.println ("abcddcba is a palindrome? " + tester.ptest ("abcddcba")); System.out.println ("able was I ere I saw elba is a palindrome? " + tester.ptest ("able was I ere I saw elba")); System.out.println ("hello is a palindrome? " + tester.ptest ("hello")); System.out.println ("abcxycba is a palindrome? " + tester.ptest ("abcxycba")); } // method main } // class Palindromes Chapter 12 Copyright 1997 by John Lewis and William Loftus. All rights reserved.

Copyright 1997 by John Lewis and William Loftus. All rights reserved. Example: Palindromes class Palindrome_Tester { // Uses recursion to perform the palindrome test. public boolean ptest (String str) { boolean result = false; if (str.length() <= 1) result = true; else if (str.charAt (0) == str.charAt (str.length()-1)) result = ptest (str.substring (1, str.length()-1)); return result; } // method ptest } // class Palindrome_Tester Chapter 12 Copyright 1997 by John Lewis and William Loftus. All rights reserved.

Copyright 1997 by John Lewis and William Loftus. All rights reserved. Using Recursion A maze is solved by trial and error -- choosing a direction, following a path, returning to a previous point if the wrong move is made As such, it is another good candidate for a recursive solution The base case is an invalid move or one which reaches the final destination See Maze_Search.java Chapter 12 Copyright 1997 by John Lewis and William Loftus. All rights reserved.

Example: Maze_Search.java public class Maze_Search { // Creates a new maze, prints its original form, attempts // to solve it, and prints out its final form. public static void main (String[] args) { Maze labyrinth = new Maze(); labyrinth.print_maze(); if (labyrinth.solve(0, 0)) System.out.println ("Maze solved!"); else System.out.println ("No solution."); } // method main } // class Maze_Search Chapter 12 Copyright 1997 by John Lewis and William Loftus. All rights reserved.

Copyright 1997 by John Lewis and William Loftus. All rights reserved. class Maze { int[][] grid = {{1,1,1,0,1,1,0,0,0,1,1,1,1}, {1,0,1,1,1,0,1,1,1,1,0,0,1}, {0,0,0,0,1,0,1,0,1,0,1,0,0}, {1,1,1,0,1,1,1,0,1,0,1,1,1}, {1,0,1,0,0,0,0,1,1,1,0,0,1}, {1,0,1,1,1,1,1,1,0,1,1,1,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0}, {1,1,1,1,1,1,1,1,1,1,1,1,1}}; // Prints the maze grid. public void print_maze () { System.out.println(); for (int row=0; row < grid.length; row++) { for (int column=0; column < grid[row].length; column++) System.out.print (grid[row][column]); } } // method print_maze Chapter 12 Copyright 1997 by John Lewis and William Loftus. All rights reserved.

Copyright 1997 by John Lewis and William Loftus. All rights reserved. // Attempts to recursively traverse the maze.. public boolean solve (int row, int column) { boolean done = false; if (valid (row, column)) { grid[row][column] = 3; // cell has been tried if (row == grid.length-1 && column == grid[0].length-1) done = true; // maze is solved else { done = solve (row+1, column); // down if (!done) done = solve (row, column+1); // right if (!done) done = solve (row-1, column); // up if (!done) done = solve (row, column-1); // left } if (done) // part of the final path grid[row][column] = 7; return done; } // method solve Chapter 12 Copyright 1997 by John Lewis and William Loftus. All rights reserved.

Copyright 1997 by John Lewis and William Loftus. All rights reserved. // Determines if a specific location is valid. private boolean valid (int row, int column) { boolean result = false; // check if cell is in the bounds of the matrix if (row >= 0 && row < grid.length && column >= 0 && column < grid[0].length) // check if cell is not blocked and not previously tried if (grid[row][column] == 1) result = true; return result; } // method valid } // class Maze Chapter 12 Copyright 1997 by John Lewis and William Loftus. All rights reserved.