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

Slides:



Advertisements
Similar presentations
The Towers of Hanoi or Apocalypse When?.
Advertisements

Recursion –a programming strategy for solving large problems –Think “divide and conquer” –Solve large problem by splitting into smaller problems of same.
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.
Kavita Math231 Recursion and Iteration. Kavita Math231 We use Recursion when we have to perform a complex task that can be broken into the several subtasks.
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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ETC - 1 What comes next? Recursion (Chapter 15) Recursive Data Structures.
1 CSCD 300 Data Structures Recursion. 2 Proof by Induction Introduction only - topic will be covered in detail in CS 320 Prove: N   i = N ( N + 1.
Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.
Fall 2007CS 2251 Recursion Chapter 7. Fall 2007CS 2252 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method.
Recursion Road Map Introduction to Recursion Recursion Example #1: World’s Simplest Recursion Program Visualizing Recursion –Using Stacks Recursion Example.
Recursion Gordon College CPS212
Recursive Algorithms Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Recursion.
Chapter 11 Recursion Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Review of Recursion. Definition: Recursion - The process of a function calling itself.
Recursion A recursive function is a function that calls itself either directly or indirectly through another function. The problems that can be solved.
Recursion Chapter 7. Chapter 7: Recursion2 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn.
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.
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.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved ADT Implementation:
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12: Recursion Problem Solving, Abstraction, and Design using C++
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved ADT Implementation:
1 Recursion Algorithm Analysis Standard Algorithms Chapter 7.
Chapter 9: Recursion1 CHAPTER 9 RECURSION. Recursion  Concept of recursion  A recursive: Benefit and Cost  Comparison : Iterative and recursive functions.
RECURSION Lecture 7 CS2110 – Fall Overview references to sections in text 2  Note: We’ve covered everything in JavaSummary.pptx!  What is recursion?
CHAPTER 02 Recursion Compiled by: Dr. Mohammad Omar Alhawarat.
Lecturer: Dr. AJ Bieszczad Chapter 11 COMP 150: Introduction to Object-Oriented Programming 11-1 l Basics of Recursion l Programming with Recursion Recursion.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 19 : Recursion King Fahd University of Petroleum & Minerals College of Computer.
1 Chapter 13 Recursion. 2 Chapter 13 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions l Writing Recursive.
Recursion Textbook chapter Recursive Function Call a recursive call is a function call in which the called function is the same as the one making.
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
ICS220 – Data Structures and Algorithms Dr. Ken Cosh Week 5.
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.
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.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
1 Recursion. 2 Chapter 15 Topics  Meaning of Recursion  Base Case and General Case in Recursive Function Definitions  Writing Recursive Functions with.
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 Chapter 17 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
1 Recursion Recursive function: a function that calls itself (directly or indirectly). Recursion is often a good alternative to iteration (loops). Its.
1 ADT Implementation: Recursion, Algorithm Analysis Chapter 10.
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.
CS212: Data Structures and Algorithms
Recursion (Continued)
Recursion.
Chapter 13 Recursion Copyright © 2016 Pearson, Inc. All rights reserved.
Lesson #6 Modular Programming and Functions.
Lesson #6 Modular Programming and Functions.
Recursion (Continued)
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Java Software Structures: John Lewis & Joseph Chase
Announcements Final Exam on August 17th Wednesday at 16:00.
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Lesson #6 Modular Programming and Functions.
Recursion "To understand recursion, one must first understand recursion." -Stephen Hawking.
CS201: Data Structures and Discrete Mathematics I
CMSC201 Computer Science I for Majors Lecture 17 – Recursion (cont)
Lesson #6 Modular Programming and Functions.
Presentation transcript:

RECURSION Lecture 6 CS2110 – Fall 2013

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 Homework. Copy our “sum the digits” method but comment out the base case. Now run it: what happens in Eclipse? Now restore the base case. Use Eclipse in debug mode and put a break statement on the “return” of the base case. Examine the stack and look at arguments to each level of the recursive call.

Recursion 3 Arises in two forms in computer science  Recursion as a mathematical tool for defining a function in terms of itself in a simpler case  Recursion as a programming tool. You’ve seen this previously but we’ll take it to mind-bending extremes (by the end of the class it will seem easy!) Mathematical induction is used to prove that a recursive function works correctly. This requires a good, precise function specification. See this in a later lecture.

Recursion as a math technique 4 Broadly, recursion is a powerful technique for defining functions, sets, and programs A few recursively-defined functions and programs  factorial  combinations  exponentiation (raising to an integer power) Some recursively-defined sets  grammars  expressions  data structures (lists, trees,...)

Example: Sum the digits in a number 5  E.g. sum(87012) = 2+(1+(0+(7+8))) = 18 /** 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 n%10 + sum(n/10); } sum calls itself!

Example: Is a string a palindrome? 6  isPal(“racecar”) = true  isPal(“pumpkin”) = 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)); } racecar aceca cec e Substring from s[1] to s[n-1]

Example: Count the e’s in a string 7  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)

Example: The Factorial Function (n!) 8 Define n! = n·(n  1)·(n  2)···3·2·1 read: “n factorial” E.g. 3! = 3·2·1 = 6 Looking at definition, can see that n! = n * (n-1)! By convention, 0! = 1 The function int  int that gives n! on input n is called the factorial function

A Recursive Program 9 /** = n!. Precondition: n >= 0 */ static int fact(int n) { if (n = = 0) return 1; // { n > 0 } return n*fact(n-1); } 0! = 1 n! = n·(n  1)!, n > 0

General Approach to Writing Recursive Functions Find base case(s) – small values of n for which you can just write down the solution (e.g. 0! = 1) 2. Try to find a parameter, say n, such that the solution for n can be obtained by combining solutions to the same problem using smaller values of n (e.g. (n-1) in our factorial example) 3. Verify that, for any valid value of n, applying the reduction of step 1 repeatedly will ultimately hit one of the base cases

Example: Tower of Hanoi Legend has it that there were three diamond needles set into the floor of the temple of Brahma in Hanoi. Stacked upon the leftmost needle were 64 golden disks, each a different size, stacked in concentric order:

A Legend The priests were to transfer the disks from the first needle to the second needle, using the third as necessary. But they could only move one disk at a time, and could never put a larger disk on top of a smaller one. When they completed this task, the world would end!

To Illustrate For simplicity, suppose there were just 3 disks, and we ’ ll refer to the three needles as A, B, and C... Since we can only move one disk at a time, we move the top disk from A to B.

Example For simplicity, suppose there were just 3 disks, and we ’ ll refer to the three needles as A, B, and C... We then move the top disk from A to C.

Example (Ct ’ d) For simplicity, suppose there were just 3 disks, and we ’ ll refer to the three needles as A, B, and C... We then move the top disk from B to C.

Example (Ct ’ d) For simplicity, suppose there were just 3 disks, and we ’ ll refer to the three needles as A, B, and C... We then move the top disk from A to B.

Example (Ct ’ d) For simplicity, suppose there were just 3 disks, and we ’ ll refer to the three needles as A, B, and C... We then move the top disk from C to A.

Example (Ct ’ d) For simplicity, suppose there were just 3 disks, and we ’ ll refer to the three needles as A, B, and C... We then move the top disk from C to B.

Example (Ct ’ d) For simplicity, suppose there were just 3 disks, and we ’ ll refer to the three needles as A, B, and C... We then move the top disk from A to B.

Example (Ct ’ d) For simplicity, suppose there were just 3 disks, and we ’ ll refer to the three needles as A, B, and C... and we ’ re done! The problem gets more difficult as the number of disks increases...

Our Problem Today ’ s problem is to write a program that generates the instructions for the priests to follow in moving the disks. While quite difficult to solve iteratively, this problem has a simple and elegant recursive solution.

General Approach to Writing Recursive Functions Find base case(s) – small values of n for which you can just write down the solution (e.g. 0! = 1) 2. Try to find a parameter, say n, such that the solution for n can be obtained by combining solutions to the same problem using smaller values of n (e.g. (n-1) in our factorial example) 3. Verify that, for any valid value of n, applying the reduction of step 1 repeatedly will ultimately hit one of the base cases

Design Basis: What is an instance of the problem that is trivial?  n == 1 Since this base case could occur when the disk is on any needle, we simply output the instruction to move the top disk from A to B.

Design Basis: What is an instance of the problem that is trivial?  n == 1 Since this base case could occur when the disk is on any needle, we simply output the instruction to move the top disk from A to B.

Design (Ct ’ d) Induction Step: n > 1  How can recursion help us out? a. Recursively move n-1 disks from A to C.

Design (Ct ’ d) Induction Step: n > 1  How can recursion help us out? b. Move the one remaining disk from A to B.

Design (Ct ’ d) Induction Step: n > 1  How can recursion help us out? c. Recursively move n-1 disks from C to B...

Design (Ct ’ d) Induction Step: n > 1  How can recursion help us out? d. We ’ re done!

Tower of Hanoi: Code void Hanoi(int n, string a, string b, string c) { if (n == 1) /* base case */ Move(a,b); else { /* recursion */ Hanoi(n-1,a,c,b); Move(a,b); Hanoi(n-1,c,b,a); }

Tower of Hanoi on Robot! 30

The Fibonacci Function 31 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

Recursive Execution 32 fib(4) fib(2) fib(0) fib(1) Execution of fib(4): fib(3) fib(0) fib(1) fib(2) /** = fibonacci(n) …*/ static int fib(int n) { if (n <= 1) return n; // { 1 < n } return fib(n-2) + fib(n-1); }

Non-Negative Integer Powers 33 a n = a·a·a···a (n times) Alternative description:  a 0 = 1  a n+1 = a·a n /** = a n. Pre: n >= 0 */ static int power(int a, int n) { if (n == 0) return 1; return a*power(a, n-1); }

A Smarter Version 34 Power computation:  a 0 = 1  If n is nonzero and even, a n = (a*a) n/2  If n is nonzero, a n = a * a n-1 Java note: For ints x and y, x/y is the integer part of the quotient Judicious use of the second property makes this a logarithmic algorithm, as we will see Example: 3 8 = (3*3) * (3*3) * (3*3) * (3*3) = (3*3) 4

Smarter Version in Java 35  n = 0: a 0 = 1  n nonzero and even: a n = (a*a) n/2  n nonzero: a n = a·a n-1 /** = 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); }

Build table of multiplications 36 nnmults 00 12**01 22** ** **34 95 … 162**45 Start with n = 0, then n = 1, etc. For each, calculate number of mults based on method body and recursion. See from the table: For n a power of 2, n = 2**k, only k+1 = (log n) + 1 mults 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); } For n = 2**15 = 32768, only 16 mults!

How Java “compiles” recursive code 37 Key idea:  Java uses a stack to remember parameters and local variables across recursive calls  Each method invocation gets its own stack frame A stack frame contains storage for  Local variables of method  Parameters of method  Return info (return address and return value)  Perhaps other bookkeeping info

Stacks 38  Like a stack of dinner plates  You can push data on top or pop data off the top in a LIFO (last-in-first-out) fashion  A queue is similar, except it is FIFO (first-in-first-out) top element 2nd element 3rd element... bottom element... top-of-stack pointer stack grows

return info local variables parameters Stack Frame 39 A new stack frame is pushed with each recursive call The stack frame is popped when the method returns  Leaving a return value (if there is one) on top of the stack a stack frame retval a, n

Example: power(2, 5) 40 return info (a = ) 2 (n = ) 5 (hP = ) ? return info (a = ) 2 (n = ) 5 (hP = ) ? return info (a = ) 2 (n = ) 2 (hP = ) ? return info (a = ) 2 (n = ) 5 (hP = ) ? return info (a = ) 2 (n = ) 2 (hP = ) ? return info (a = ) 2 (n = ) 1 (hP = ) ? return info (a = ) 2 (n = ) 5 (hP = ) 4 return info (a = ) 2 (n = ) 5 (hP = ) ? return info (a = ) 2 (n = ) 2 (hP = ) 2 return info (a = ) 2 (n = ) 5 (hP = ) ? return info (a = ) 2 (n = ) 2 (hP = ) ? return info (a = ) 2 (n = ) 1 (hP = ) 1 (retval = ) 1 (retval = ) 2 (retval = ) 4 (retval = ) 32 hP: short for halfPower

How Do We Keep Track? 41  Many frames may exist, but computation occurs only in the top frame  The ones below it are waiting for results  The hardware has nice support for this way of implementing function calls, and recursion is just a kind of function call

Conclusion 42 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 Important application (next lecture): parsing

Extra Slides 43

A cautionary note 44  Keep in mind that each instance of the recursive function has its own local variables  Also, remember that “higher” instances are waiting while “lower” instances run  Do not touch global variables from within recursive functions  Legal … but a common source of errors  Must have a really clear mental picture of how recursion is performed to get this right!

Memoization (fancy term for “caching”) 45 Memoization is an optimization technique used to speed up computer programs by having function calls avoid repeating the calculation of results for previously processed inputs.  First time the function is called, save result  Next times, look up the result 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

One thing to notice: Fibonacci 46 This way of computing the Fibonacci function is elegant but inefficient It “recomputes” answers again and again! To improve speed, need to save known answers in a table!  One entry per answer  Such a table is called a cache fib(4) fib(2) fib(0) fib(1) fib(3) fib(0) fib(1) fib(2)

Adding Memoization to our solution Before memoization: 47 static int fib(int n) { if (n <= 1) return n; return fib(n-2) + fib(n-1); } /** 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; if (n <= 1) v= n; else v= fib(n-2) + fib(n-1); if (n == cached.size()) cached.add(v); return v; } After Memoization This works because of definition of cached 48 This appends v to cached, keeping cached’s definition true

Notice the development process 49  We started with the idea of recursion  Created a very simple recursive procedure  Noticed it will be slow because it wastefully recomputes the same thing again and again  We made it a bit more complex but gained a lot of speed in doing so  This is a common software engineering pattern

Why did it work? 50  This cached list “works” because for each value of n, either cached.get(n) is still undefined or has fib(n)  Takes advantage of the fact that an ArrayList adds elements at the end and indexes from size=5 cached.get(0) = 0 cached.get(1) = 1 … cached.get(n) = fib(n) Property of our code: cached.get(n) accessed after fib(n) computed