RECURSION Lecture 7 CS2110 – Fall 2014. Overview references to sections in text 2  Note: We’ve covered everything in JavaSummary.pptx!  What is recursion?

Slides:



Advertisements
Similar presentations
Recursion –a programming strategy for solving large problems –Think “divide and conquer” –Solve large problem by splitting into smaller problems of same.
Advertisements

Recursive Functions The Fibonacci function shown previously is recursive, that is, it calls itself Each call to a recursive method results in a separate.
Recursion. Recursive Definitions A recursive definition is one which uses the word being defined in the definition Not always useful:  for example, in.
RECURSION Lecture 6 CS2110 – Fall Recursion Overview 4  Recursion is a powerful technique for specifying functions, sets, and programs 
Computer Science II Recursion Professor: Evan Korth New York University.
CS102 Algorithms and Programming II1 Recursion Recursion is a technique that solves a problem by solving a smaller problem of the same type. A recursive.
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.
Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.
Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.
CS 206 Introduction to Computer Science II 10 / 14 / 2009 Instructor: Michael Eckmann.
1 Executing Method Calls This lecture tells you precisely how method calls are executed (a few details will have to wait until we get to classes and objects).
Recursion Road Map Introduction to Recursion Recursion Example #1: World’s Simplest Recursion Program Visualizing Recursion –Using Stacks Recursion Example.
Chapter 11 Recursion Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Stacks. What is a stack? A stack is a Last In, First Out (LIFO) data structure Anything added to the stack goes on the “top” of the stack Anything removed.
90-723: Data Structures and Algorithms for Information Processing Copyright © 1999, Carnegie Mellon. All Rights Reserved. Lecture 8: Recursion Data Structures.
Unit 7 1 Unit 7: Recursion H Recursion is a fundamental programming technique that can provide an elegant solution to a certain kinds of problems H In.
1 Assignment 8. Implementing type integer Due on Tuesday, 4 December, by midnight (submitted electronically). Download class List and a skeleton of class.
Building Java Programs
RECURSION Lecture 7 CS2110 – Spring Overview references to sections in text 2  Note: We’ve covered everything in JavaSummary.pptx!  What is recursion?
Introduction to Programming (in C++) Recursion Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC.
A Review of Recursion Dr. Jicheng Fu Department of Computer Science University of Central Oklahoma.
20-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN
Recursion Chapter Nature of Recursion t Problems that lend themselves to a recursive solution have the following characteristics: –One or more.
Recursion. Basic problem solving technique is to divide a problem into smaller subproblems These subproblems may also be divided into smaller subproblems.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12: Recursion Problem Solving, Abstraction, and Design using C++
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 Lecture 6 CS2110 – Fall Overview references to sections in text 2  Note: We’ve covered everything in JavaSummary.pptx!  What is recursion?
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 9: Recursion1 CHAPTER 9 RECURSION. Recursion  Concept of recursion  A recursive: Benefit and Cost  Comparison : Iterative and recursive functions.
Nonvisual Arrays and Recursion by Chris Brown under Prof. Susan Rodger Duke University June 2012.
Stephen P. Carl - CS 2421 Recursion Reading : Chapter 4.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 19 : Recursion King Fahd University of Petroleum & Minerals College of Computer.
CIS 068 Welcome to CIS 068 ! Stacks and Recursion.
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
Chapter 13 Recursion. Learning Objectives Recursive void Functions – Tracing recursive calls – Infinite recursion, overflows Recursive Functions that.
Recursion Recursion Chapter 12. Outline n What is recursion n Recursive algorithms with simple variables n Recursion and the run-time stack n Recursion.
Recursion. What is recursion? Rules of recursion Mathematical induction The Fibonacci sequence Summary Outline.
RECURSION Lecture 6 CS2110 – Fall Overview references to sections in text 2  Note: We’ve covered everything in JavaSummary.pptx!  What is recursion?
CSC 221: Recursion. Recursion: Definition Function that solves a problem by relying on itself to compute the correct solution for a smaller version of.
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.
Stacks and Queues. 2 3 Runtime Efficiency efficiency: measure of computing resources used by code. can be relative to speed (time), memory (space), etc.
Generics with ArrayList and HashSet 1 ge·ner·ic adjective \jə ̇ˈ nerik, -rēk\ relating or applied to or descriptive of all members of a genus, species,
RECURSION, CONTINUED Lecture 8 CS2110 – Fall 2015.
RECURSION Lecture 6 CS2110 – Spring Recursion 2  Arises in three forms in computer science  Recursion as a mathematical tool for defining a function.
RECURSION Lecture 7 CS2110 – Fall Overview references to sections in text 2  Note: We’ve covered everything in JavaSummary.pptx!  What is recursion?
CS/ENGRD 2110 FALL 2013 Lecture 3: Fields, getters and setters, constructors, testing 1.
1 Recursion Recursive function: a function that calls itself (directly or indirectly). Recursion is often a good alternative to iteration (loops). Its.
1 Recursion and induction We teach these early, instead of new object- oriented ideas, so that those who are new to Java can have a chance to catch up.
RECURSION Lecture 8 CS2110 – Fall Overview references to sections in text 2  Note: We’ve covered everything in JavaSummary.pptx!  What is recursion?
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Recursion,
RECURSION (CONTINUED) Lecture 9 CS2110 – Spring 2016.
Recursion (Continued)
Recursion.
Data Structures with Java © Rick Mercer
Introduction to Recursion
Introduction to Computer Science / Procedural – 67130
Recursion (Continued)
Recursion (Continued)
Recursion "To understand recursion, one must first understand recursion." -Stephen Hawking.
Applied Algorithms (Lecture 17) Recursion Fall-23
Algorithm design and Analysis
CS201: Data Structures and Discrete Mathematics I
Recursion (Continued)
Unit 3 Test: Friday.
Recursion (Continued)
Presentation transcript:

RECURSION Lecture 7 CS2110 – Fall 2014

Overview references to sections in text 2  Note: We’ve covered everything in JavaSummary.pptx!  What is recursion? slide 1-7  Base case slide 13  How Java stack frames work slide 28-32

A little about generics –used in A3 3 public class DLinkedList { …} // E is a type parameter /** Values in d1 can be ANY objects —String, JFrame, etc. */ DLinkedList d1= new DLinkedList(); … String x= ((String) d1.getHead()).getValueOf(); // cast is needed /** The values in d2 are only objects of class String */ DLinkedList d2= new DLinkedList (); … String s= d2.getHead().getValueOf(); // no cast is needed

What does generic mean? 4 From Merriam-Webster online: ge·ner·ic adjective a : relating or applied to or descriptive of all members of a genus, species, class, or group : common to or characteristic of a whole group or class : typifying or subsuming : not specific or individual generic applies to that which characterizes every individual in a category or group and may suggest further that what is designated may be thought of as a clear and certain classificatory criterion

Sum the digits in a non-negative integer 5 E.g. sum(7) = 7 /** return sum of digits in n. * Precondition: n >= 0 */ public static int sum(int n) { if (n < 10) return n; // { n has at least two digits } // return first digit + sum of rest return sum(n/10) + n%10 ; } sum calls itself! E.g. sum(8703) = sum(870) + 3;

Two issues with recursion 6 1. Why does it work? How does it execute? /** return sum of digits in n. * Precondition: n >= 0 */ public static int sum(int n) { if (n < 10) return n; // { n has at least two digits } // return first digit + sum of rest return sum(n/10) + n%10 + ; } sum calls itself! 2. How do we understand a given recursive method, or how do we write/develop a recursive method?

Stacks and Queues 7 top element 2nd element... bottom element stack grows Stack: list with (at least) two basic ops: * Push an element onto its top * Pop (remove) top element Last-In-First-Out (LIFO) Like a stack of trays in a cafeteria first second … last Queue: list with (at least) two basic ops: * Append an element * Remove first element First-In-First-Out (FIFO) Americans wait in a line, the Brits wait in a queue !

local variables parameters return info Stack Frame 8 a frame A “frame” contains information about a method call: At runtime, Java maintains a stack that contains frames for all method calls that are being executed but have not completed. Method call: push a frame for call on stack, assign argument values to parameters, execute method body. Use the frame for the call to reference local variables, parameters. End of method call: pop its frame from the stack; if it is a function, leave the return value on top of stack.

Example: Sum the digits in a non-negative integer 9 public static int sum(int n) { if (n < 10) return n; return sum(n/10) + n%10; } public static void main(…) { int r= sum(824); System.out.println(r); } frame: n ___ return info frame: r ___ args ___ return info frame: ? return info Frame for method in the system that calls method main

Example: Sum the digits in a non-negative integer 10 public static int sum(int n) { if (n < 10) return n; return sum(n/10) + n%10); } public static void main(…) { int r= sum(824); System.out.println(r); } ? return info Frame for method in the system that calls method main: main is then called system r ___ args ___ return info main

Example: Sum the digits in a non-negative integer 11 public static int sum(int n) { if (n < 10) return n; return sum(n/10) + n%10 ; } public static void main(…) { int r= sum(824); System.out.println(r); } ? return info Method main calls sum: system r ___ args ___ return info main n ___ return info 824

Example: Sum the digits in a non-negative integer 12 public static int sum(int n) { if (n < 10) return n; return sum(n/10) + n%10; } public static void main(…) { int r= sum(824); System.out.println(r); } ? return info n >= 10, sum calls sum: system r ___ args ___ return info main n ___ return info 824 n ___ return info 82

Example: Sum the digits in a non-negative integer 13 public static int sum(int n) { if (n < 10) return n; return sum(n/10) + n%10; } public static void main(…) { int r= sum(824); System.out.println(r); } ? return info n >= 10. sum calls sum: system r ___ args ___ return info main n ___ return info 824 n ___ return info 82 n ___ return info 8 10

Example: Sum the digits in a non-negative integer 14 public static int sum(int n) { if (n < 10) return n; return sum(n/10) + n%10; } public static void main(…) { int r= sum(824); System.out.println(r); } ? return info n < 10, sum stops: frame is popped and n is put on stack: system r ___ args ___ return info main n ___ return info 824 n ___ return info 82 n ___ return info 8 8

Example: Sum the digits in a non-negative integer 15 public static int sum(int n) { if (n < 10) return n; return sum(n/10) + n%10; } public static void main(…) { int r= sum(824); System.out.println(r); } ? return info Using return value 8, stack computes = 10, pops frame from stack, puts return value 10 on stack r ___ args ___ return info main n ___ return info 824 n ___ return info

Example: Sum the digits in a non-negative integer 16 public static int sum(int n) { if (n < 10) return n; return sum(n/10) + n%10; } public static void main(…) { int r= sum(824); System.out.println(r); } ? return info Using return value 10, stack computes = 14, pops frame from stack, puts return value 14 on stack r ___ args ___ return info main n ___ return info

Example: Sum the digits in a non-negative integer 17 public static int sum(int n) { if (n < 10) return n; return sum(n/10) + n%10; } public static void main(…) { int r= sum(824); System.out.println(r); } ? return info Using return value 14, main stores 14 in r and removes 14 from stack r ___ args __ return info main 14

Summary of method call execution 18 Memorize this!  1. A frame for a call contains parameters, local variables, and other information needed to properly execute a method call.  2. To execute a method call: push a frame for the call on the stack, assign arg values to pars, and execute method body. When executing method body, look in frame for call for parameters and local variables. When method body finishes, pop frame from stack and (for a function) push the return value on the stack.  For function call: When control given back to call, it pops the return value and uses it as the value of the function call.

Questions about local variables 19 public static void m(…) { … while (…) { int d= 5; … } In a call m(), when is local variable d created and when is it destroyed? Which version of procedure m do you like better? Why? public static void m(…) { int d; … while (…) { d= 5; … }

Recursion is used extensively in math 20 Math definition of n factorial E.g. 3! = 3*2*1 = 6 0! = 1 n! = n * (n-1)! for n > 0 Math definition of b c for c >= 0 b 0 = 1 b c = b * b c-1 for c > 0 Easy to make math definition into a Java function! public static int fact(int n) { if (n == 0) return 1; return n * fact(n-1); } Lots of things defined recursively: expression, grammars, trees, …. We will see such things later

Two views of recursive methods 21  How are calls on recursive methods executed? We saw that. Use this only to gain understanding / assurance that recursion works  How do we understand a recursive method — know that it satisfies its specification? How do we write a recursive method? This requires a totally different approach. Thinking about how the method gets executed will confuse you completely! We now introduce this approach.

Understanding a recursive method 22 Step 1. Have a precise spec! /** = sum of digits of n. * Precondition: n >= 0 */ public static int sum(int n) { if (n < 10) return n; // n has at least two digits return sum(n/10) + n%10 ; } Step 2. Check that the method works in the base case(s): Cases where the parameter is small enough that the result can be computed simply and without recursive calls. If n < 10, then n consists of a single digit. Looking at the spec, we see that that digit is the required sum.

Step 3. Look at the recursive case(s). In your mind, replace each recursive call by what it does according to the method spec and verify that the correct result is then obtained. return sum(n/10) + n%10; Understanding a recursive method 23 Step 1. Have a precise spec! /** = sum of digits of n. * Precondition: n >= 0 */ public static int sum(int n) { if (n < 10) return n; // n has at least two digits return sum(n/10) + n%10 ; } Step 2. Check that the method works in the base case(s). return (sum of digits of n/10) + n%10; // e.g. n = 843

Step 3. Look at the recursive case(s). In your mind, replace each recursive call by what it does acc. to the spec and verify correctness. Understanding a recursive method 24 Step 1. Have a precise spec! /** = sum of digits of n. * Precondition: n >= 0 */ public static int sum(int n) { if (n < 10) return n; // n has at least two digits return sum(n/10) + n%10 ; } Step 2. Check that the method works in the base case(s). Step 4. (No infinite recursion) Make sure that the args of recursive calls are in some sense smaller than the pars of the method. n/10 < n

Step 3. Look at the recursive case(s). In your mind, replace each recursive call by what it does according to the spec and verify correctness. Understanding a recursive method 25 Step 1. Have a precise spec! Step 2. Check that the method works in the base case(s). Step 4. (No infinite recursion) Make sure that the args of recursive calls are in some sense smaller than the pars of the method Important! Can’t do step 3 without it Once you get the hang of it, this is what makes recursion easy! This way of thinking is based on math induction, which we will see later in the course.

Step 3. Look at all other cases. See how to define these cases in terms of smaller problems of the same kind. Then implement those definitions, using recursive calls for those smaller problems of the same kind. Done suitably, point 4 is automatically satisfied. Writing a recursive method 26 Step 1. Have a precise spec! Step 2. Write the base case(s): Cases in which no recursive calls are needed Generally, for “small” values of the parameters. Step 4. (No infinite recursion) Make sure that the args of recursive calls are in some sense smaller than the pars of the method

Step 3. Look at all other cases. See how to define these cases in terms of smaller problems of the same kind. Then implement those definitions, using recursive calls for those smaller problems of the same kind. Examples of writing recursive functions 27 Step 1. Have a precise spec! Step 2. Write the base case(s). For the rest of the class, we demo writing recursive functions using the approach outlined below. The java file we develop will be placed on the course webpage some time after the lecture.

The Fibonacci Function 28 Mathematical definition: fib(0) = 0 fib(1) = 1 fib(n) = fib(n  1) + fib(n  2), n ≥ 2 Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, … /** = fibonacci(n). Pre: n >= 0 */ static int fib(int n) { if (n <= 1) return n; // { 1 < n } return fib(n-2) + fib(n-1); } two base cases! Fibonacci (Leonardo Pisano) ? Statue in Pisa, Italy Giovanni Paganucci 1863

Example: Is a string a palindrome? 29 isPal(“racecar”) returns true isPal(“pumpkin”) returns false /** = "s is a palindrome" */ public static boolean isPal(String s) { if (s.length() <= 1) return true; // { s has at least 2 chars } int n= s.length()-1; return s.charAt(0) == s.charAt(n) && isPal(s.substring(1, n)); } Substring from s[1] to s[n-1]

Example: Count the e’s in a string 30  countEm(‘e’, “it is easy to see that this has many e’s”) = 4  countEm(‘e’, “Mississippi”) = 0 /** = number of times c occurs in s */ public static int countEm(char c, String s) { if (s.length() == 0) return 0; // { s has at least 1 character } if (s.charAt(0) != c) return countEm(c, s.substring(1)); // { first character of s is c} return 1 + countEm (c, s.substring(1)); } substring s[1..], i.e. s[1], …, s(s.length()-1)

Computing a n for n >= 0 31 Power computation:  a 0 = 1  If n != 0, a n = a * a n-1  If n != 0 and even, a n = (a*a) n/2 Java note: For ints x and y, x/y is the integer part of the quotient Judicious use of the third property gives a logarithmic algorithm, as we will see Example: 3 8 = (3*3) * (3*3) * (3*3) * (3*3) = (3*3) 4

Computing a n for n >= 0 32 /** = a**n. Precondition: n >= 0 */ static int power(int a, int n) { if (n == 0) return 1; if (n%2 == 0) return power(a*a, n/2); return a * power(a, n-1); } Power computation:  a 0 = 1  If n != 0, a n = a * a n-1  If n != 0 and even, a n = (a*a) n/2

Conclusion 33 Recursion is a convenient and powerful way to define functions Problems that seem insurmountable can often be solved in a “divide-and-conquer” fashion:  Reduce a big problem to smaller problems of the same kind, solve the smaller problems  Recombine the solutions to smaller problems to form solution for big problem

Extra material: memoization 34 /** = fibonacci(n), for n >= 0 */ static int fib(int n) { if (n <= 1) return n; // { 1 < n } return fib(n-2) + fib(n-1); } fib(4) fib(2) fib(0) fib(1) fib(3) fib(0) fib(1) fib(2) Execution of fib(4) is inefficient. E.g. in the tree to right, you see 3 calls of fib(1). To speed it up, save values of fib(i) in a table as they are calculated. For each i, fib(i) called only once. The table is called a cache

Memoization (fancy term for “caching”) 35 Memoization: an optimization technique used to speed up execution by having function calls avoid repeating the calculation of results for previously processed inputs.  The first time the function is called, save result  The next time, look the result up Assumes a “side effect free” function: The function just computes the result, it doesn’t change things If the function depends on anything that changes, must “empty” the saved results list

Adding memoization to our solution Before memoization: 36 static int fib(int n) { int v= n <= 1 ? n : fib(n-1) + fib(n-2); return v; } /** For 0 <= k < cached.size(), cached[k] = fib(k) */ static ArrayList cached= new ArrayList (); The list used to memoize

/** For 0 <= k < cached.size(), cached[k] = fib(k) */ static ArrayList cached= new ArrayList (); static int fib(int n) { if (n < cached.size()) return cached.get(n); int v= n <= 1 ? n : fib(n-1) + fib(n-2); if (n == cached.size()) cached.add(v); return v; } After memoization This works because of definition of cached 37 Appends v to cached, keeping cached’s definition true

/** For 0 <= k < cached.size(), cached[k] = fib(k) */ static ArrayList cached= new ArrayList (); static int fib(int n) { if (n < cached.size()) return cached.get(n); int v= n <= 1 ? n : fib(n-1) + fib(n-2); if (n == cached.size()) cached.add(v); return v; } Memoization uses a static field 38 Recursive functions should NOT use static fields. It just doesn’t work. Don’t try to write recursive functions that way. The one case that it works is suitably written memoization.