Lecture 6 CS2110 Spring 2013 RECURSION

Similar documents
RECURSION. Many Slides from Ken Birman, Cornell University

Lecture 7 CS2110 Fall 2014 RECURSION

9/16/14. Overview references to sections in text RECURSION. What does generic mean? A little about generics used in A3

Lecture 6: Recursion RECURSION

OVERVIEW. Recursion is an algorithmic technique where a function calls itself directly or indirectly. Why learn recursion?

CS 3410 Ch 7 Recursion

6.001 Notes: Section 4.1

Identify recursive algorithms Write simple recursive algorithms Understand recursive function calling

Anatomy of a static method, S&W, 2.1, figure page 188. Class.name or just name Scope, S&W, 2.1, figure page 189. Overloading

Recursion. Recursion [Bono] 1

Recursive Definitions

Lecture 5: Recursion. Recursion Overview. Recursion is a powerful technique for specifying funclons, sets, and programs

APCS-AB: Java. Recursion in Java December 12, week14 1

COMP-202. Recursion. COMP Recursion, 2011 Jörg Kienzle and others

Announcements. Recursion and why study it. Recursive programming. Recursion basic idea

Unit #3: Recursion, Induction, and Loop Invariants

Design and Analysis of Algorithms Prof. Madhavan Mukund Chennai Mathematical Institute. Module 02 Lecture - 45 Memoization

Recursion. Tracing Method Calls via a Stack. Beyond this lecture...

Recursive definition: A definition that is defined in terms of itself. Recursive method: a method that calls itself (directly or indirectly).

CSCE 110 Dr. Amr Goneid Exercise Sheet (7): Exercises on Recursion

COMP 202 Recursion. CONTENTS: Recursion. COMP Recursion 1

Lecture 19: Recursion

Unit #2: Recursion, Induction, and Loop Invariants

If you are going to form a group for A2, please do it before tomorrow (Friday) noon GRAMMARS & PARSING. Lecture 8 CS2110 Spring 2014

Lecture 12: Dynamic Programming Part 1 10:00 AM, Feb 21, 2018

/633 Introduction to Algorithms Lecturer: Michael Dinitz Topic: Priority Queues / Heaps Date: 9/27/17

Recursion: Factorial (1) Recursion. Recursion: Principle. Recursion: Factorial (2) Recall the formal definition of calculating the n factorial:

Wentworth Institute of Technology COMP1050 Computer Science II Spring 2017 Derbinsky. Recursion. Lecture 13. Recursion

CS 310 Advanced Data Structures and Algorithms

CPSC 221: Algorithms and Data Structures Lecture #1: Stacks and Queues

Building Java Programs

Recursion. EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG

Recursion. So, just as you are allowed to call function B from within function A, you are ALSO allowed to call function A from within function A!

Lecture 10: Recursion vs Iteration

RECURSION (CONTINUED)

Recursion Chapter 8. What is recursion? How can a function call itself? How can a function call itself?

Recursion. Fundamentals of Computer Science

GRAMMARS & PARSING. Lecture 7 CS2110 Fall 2013

Lecture P6: Recursion

# track total function calls using a global variable global fibcallcounter fibcallcounter +=1

Lecture 16: Introduction to Dynamic Programming Steven Skiena. Department of Computer Science State University of New York Stony Brook, NY

CSE 143 Lecture 10. Recursive Programming. reading: slides adapted from Marty Stepp and Hélène Martin

Recursion CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2011

6.001 Notes: Section 15.1

CSE 2123 Recursion. Jeremy Morris

Reduction & Recursion Overview

Tail Calls. CMSC 330: Organization of Programming Languages. Tail Recursion. Tail Recursion (cont d) Names and Binding. Tail Recursion (cont d)

Data Structures And Algorithms

CS61C : Machine Structures

CSE 143 Lecture 11. Decimal Numbers

Procedures and Stacks

EECE.3170: Microprocessor Systems Design I Summer 2017 Homework 4 Solution

RECURSION 7. 1 Recursion COMPUTER SCIENCE 61A. October 15, 2012

STUDENT LESSON A9 Recursion

CSE 143. Computer Programming II

CMPSCI 250: Introduction to Computation. Lecture #14: Induction and Recursion (Still More Induction) David Mix Barrington 14 March 2013

COMP-202: Foundations of Programming. Lecture 13: Recursion Sandeep Manjanna, Summer 2015

Recursion Chapter 8. What is recursion? How can a function call itself? How can a function call itself? contains a reference to itself.

CSE373: Data Structure & Algorithms Lecture 23: More Sorting and Other Classes of Algorithms. Catie Baker Spring 2015

q To develop recursive methods for recursive mathematical functions ( ).

q To develop recursive methods for recursive mathematical functions ( ).

C22a: Problem Solving using Recursion

Programming & Data Structure

The power of logarithmic computations. Recursive x y. Calculate x y. Can we reduce the number of multiplications?

Unit-5 Dynamic Programming 2016

Recursion. Overview. Mathematical induction. Hello recursion. Recursion. Example applications. Goal: Compute factorial N! = 1 * 2 * 3...

Chapter 13. Recursion. Copyright 2016 Pearson, Inc. All rights reserved.

Language of the Machine Recursive functions

CS 380 ALGORITHM DESIGN AND ANALYSIS

1/30/2018. Conventions Provide Implicit Information. ECE 220: Computer Systems & Programming. Arithmetic with Trees is Unambiguous

Department of Computer Science & Engineering Indian Institute of Technology Kharagpur. Practice Sheet #06

Queue ADT. January 31, 2018 Cinda Heeren / Geoffrey Tien 1

Csci 102: Sample Exam

Chapter 5: Recursion. Objectives

Project Compiler. CS031 TA Help Session November 28, 2011

Stacks. stacks of dishes or trays in a cafeteria. Last In First Out discipline (LIFO)

1 Dynamic Programming

Introduction to Scientific Computing

Admin. How's the project coming? After these slides, read chapter 13 in your book. Quizzes will return

RECURSION, RECURSION, (TREE) RECURSION! 2

COMP-202. Recursion. COMP Recursion, 2013 Jörg Kienzle and others

CS 101: Computer Programming and Utilization

Two Approaches to Algorithms An Example (1) Iteration (2) Recursion

CS103 Handout 29 Winter 2018 February 9, 2018 Inductive Proofwriting Checklist

/633 Introduction to Algorithms Lecturer: Michael Dinitz Topic: Sorting lower bound and Linear-time sorting Date: 9/19/17

More Complicated Recursion CMPSC 122

The Art of Recursion: Problem Set 10

We cover recursion in 150. Why do it again in 151?

Function Calling Conventions 2 CS 64: Computer Organization and Design Logic Lecture #10

Recursion vs Induction. CS3330: Algorithms The University of Iowa

CS 206 Introduction to Computer Science II

RECURSION, RECURSION, (TREE) RECURSION! 3

Functions. CS10001: Programming & Data Structures. Sudeshna Sarkar Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur

What is Iteration? CMPT-101. Recursion. Understanding Recursion. The Function Header and Documentation. Recursively Adding Numbers

Turn in a printout of your code exercises stapled to your answers to the written exercises at 2:10 PM on Thursday, January 13th.

Chapter 12 Supplement: Recursion with Java 1.5. Mr. Dave Clausen La Cañada High School

Chapter 5: Recursion

n! = 1 * 2 * 3 * 4 * * (n-1) * n

What is recursion? Recursion. How can a function call itself? Recursive message() modified. Week 10. contains a reference to itself.

CS1 Lecture 15 Feb. 19, 2018

Transcription:

Lecture 6 CS2110 Spring 2013 RECURSION

Recursion 2 Arises in three forms in computer science Recursion as a mathematical tool for defining a function in terms of its own value 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!) Recursion used to prove properties about algorithms. We use the term induction for this and will discuss it later.

Recursion as a math technique 3 Broadly, recursion is a powerful technique for specifying 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 4 /** return sum of digits in n, given n >= 0 */ public static int sum(int n) { if (n < 10) return n; sum calls itself! } // n has at least two digits: // return first digit + sum of rest return n%10 + sum(n/10); E.g. sum(87012) = 2+(1+(0+(7+8))) = 18

Example: Is a string a palindrome? 5 /** = "s is a palindrome" */ public static boolean ispalindrome(string s) { if (s.length() <= 1) return true; } Substring from char(1) to char(n-1) // s has at least 2 chars int n= s.length()-1; return s.charat(0) == s.charat(n) && ispalindrome(s.substring(1, n)); ispalindrome( racecar ) = true ispalindrome( pumpkin ) = false r a c e c a r a c e c a c e c e

Count the e s in a string 6 /** = " 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)); Substring from char(1) to end } // { first character of s is c} return 1 + countem (c, s.substring(1)); countem( e, it is easy to see that this has many e s ) = 4 countem( e, Mississippi ) = 0

The Factorial Function (n!) 7 Define n! = n (n 1) (n 2) 3 2 1 read: n factorial E.g., 3! = 3 2 1 = 6 By convention, 0! = 1 The function int int that gives n! on input n is called the factorial function

The Factorial Function (n!) 8 n! is the number of permutations of n distinct objects There is just one permutation of one object. 1! = 1 There are two permutations of two objects: 2! = 2 1 2 2 1 There are six permutations of three objects: 3! = 6 1 2 3 1 3 2 2 1 3 2 3 1 3 1 2 3 2 1 If n > 0, n! = n (n 1)!

Permutations of 9 Permutations of non-orange blocks Each permutation of the three nonorange blocks gives four permutations when the orange block is included Total number = 4 3! = 4 6 = 24: 4!

Observation 10 One way to think about the task of permuting the four colored blocks was to start by computing all permutations of three blocks, then finding all ways to add a fourth block And this explains why the number of permutations turns out to be 4! Can generalize to prove that the number of permutations of n blocks is n!

A Recursive Program 11 0! = 1 n! = n (n 1)!, n > 0 static int fact(int n) { if (n = = 0) return 1; else return n*fact(n-1); } Execution of fact(4) fact(4) fact(3) fact(2) fact(1) fact(0) 6 2 1 1 24

12 General Approach to Writing Recursive Functions 1. 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) 2. Find base case(s) small values of n for which you can just write down the solution (e.g., 0! = 1) 3. Verify that, for any valid value of n, applying the reduction of step 1 repeatedly will ultimately hit one of the base cases

A cautionary note 13 Keep in mind that each instance of your recursive function has its own local variables Also, remember that higher instances are waiting while lower instances run Not such a good idea to 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!

The Fibonacci Function 14 Mathematical definition: fib(0) = 0 fib(1) = 1 fib(n) = fib(n 1) + fib(n 2), n 2 two base cases! Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, static int fib(int n) { if (n == 0) return 0; else if (n == 1) return 1; else return fib(n-2) + fib(n-1); } Fibonacci (Leonardo Pisano) 1170 1240? Statue in Pisa, Italy Giovanni Paganucci 1863

Recursive Execution 15 static int fib(int n) { if (n == 0) return 0; else if (n == 1) return 1; else return fib(n-2) + fib(n-1); } Execution of fib(4): fib(4) fib(2) fib(3) fib(0) fib(1) fib(1) fib(2) fib(0) fib(1)

One thing to notice 16 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! fib(4) One entry per answer Such a table is called a cache fib(2) fib(3) fib(0) fib(1) fib(1) fib(2) fib(0) fib(1)

Memoization (fancy term for caching ) 17 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. The first time the function is called, we save result The next time, we can 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

18 Adding Memoization to our solution Before: After static ArrayList<Integer> cached = new ArrayList<Integer>(); static int fib(int n) { if (n == 0) static int fib(int n) { return 0; if(n < cached.size()) else if (n == 1) return cached.get(n); return 1; int v; else if (n == 0) return fib(n-2) + fib(n-1); v = 0; } else if (n == 1) v = 1; else v = fib(n-2) + fib(n-1); // cached[n] = fib(n). This code makes use of the fact // that an ArrayList adds elements to the end of the list if(n == cached.size()) cached.add(v); return v; }

Notice the development process 19 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 So 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? 20 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 0 cached@ba8900, size=5 0 1 1 2 3 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

Positive Integer Powers 21 a n = a a a a (n times) Alternate description: a 0 = 1 a n+1 = a a n static int power(int a, int n) { if (n == 0) return 1; else return a*power(a,n-1); }

A Smarter Version 22 Power computation: a0 = 1 If n is nonzero and even, an = (an/2)2 If n is odd, an = a (an/2)2 Java note: If x and y are integers, x/y returns the integer part of the quotient Example: a5 = a (a5/2)2 = a (a2)2 = a ((a2/2)2)2 = a (a2)2 Note: this requires 3 multiplications rather than 5!

A Smarter Version 23 Example: a5 = a (a5/2)2 = a (a2)2 = a ((a2/2)2)2 = a (a2)2 Note: this requires 3 multiplications rather than 5! What if n were larger? Savings would be more significant This is much faster than the straightforward computation Straightforward computation: n multiplications Smarter computation: log(n) multiplications

Smarter Version in Java 24 n = 0: a 0 = 1 n nonzero and even: a n = (a n/2 ) 2 n nonzero and odd: a n = a (a n/2 ) 2 local variable parameters static int power(int a, int n) { if (n == 0) return 1; int halfpower = power(a,n/2); if (n%2 == 0) return halfpower*halfpower; return halfpower*halfpower*a; } The method has two parameters and a local variable Why aren t these overwritten on recursive calls?

How Java compiles recursive code 25 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 26 stack grows top element 2nd element 3rd element...... bottom element top-of-stack pointer 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)

27 Stack Frame 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 halfpower local variables a, n parameters retval return info

Example: power(2, 5) 28 hp: short for halfpower (hp = )? (n = ) 1 (a = ) 2 (retval = ) 1 (hp = ) 1 (n = ) 1 (a = ) 2 (hp = )? (n = ) 2 (a = ) 2 return info (hp = )? (n = ) 2 (a = ) 2 return info (hp = )? (n = ) 2 (a = ) 2 (retval = ) 2 (hp = ) 2 (n = ) 2 (a = ) 2 (hp = )? (n = ) 5 (a = ) 2 return info (hp = )? (n = ) 5 (a = ) 2 return info (hp = )? (n = ) 5 (a = ) 2 return info (hp = )? (n = ) 5 (a = ) 2 return info (hp = )? (n = ) 5 (a = ) 2 (retval = ) 4 (hp = ) 4 (n = ) 5 (a = ) 2 return info return info return info return info return info return info (retval = ) 32

How Do We Keep Track? 29 Many frames may exist, but computation is only occurring 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 30 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 31 For use if we have time for one more example of recursion This builds on the ideas in the Fibonacci example

32 Combinations (a.k.a. Binomial Coefficients) How many ways can you choose r items from n a set of n distinct elements? ( ) n choose r 5 ( ) = number of 2-element subsets of {A,B,C,D,E} 2 r 2-element subsets containing A: {A,B}, {A,C}, {A,D}, {A,E} 2-element subsets not containing A: {B,C},{B,D},{B,E},{C,D},{C,E},{D,E} Therefore, = + 5 2 ( ) 4 4 ( ) 1 ( 1 ) ( 2) in perfect form to write a recursive function! 4 4 ( 2)

33 Combinations n ( ) n ( n) n ( 0) n 1 n 1 = + r 1, n > r > 0 = 1 = 1 r ( r ) ( ) n r ( ) Can also show that = n! r!(n r)! 0 ( 0) 1 1 ( 0) ( 1) 2 2 2 ( 0) ( 1) ( 2) 3 3 3 3 ( 0) ( 1) ( 2) ( 3) 4 4 4 4 4 ( 0) ( 1) ( 2) ( 3) ( 4) Pascal s triangle = 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1

34 Binomial Coefficients Combinations are also called binomial coefficients because they appear as coefficients in the expansion of the binomial power (x+y) n : (x + y) n = x n + x n 1 y + 2 x n 2 y 2 + + ( n) y n n n ( ) n = i x n i y i i= 0 n ( 0 ) ( 1 ) ( ) n n 34

Combinations Have Two Base Cases 35 n ( ) n ( n) n ( 0) n 1 n 1 = + r 1, n > r > 0 = 1 = 1 r ( r ) ( ) Two base cases Coming up with right base cases can be tricky! General idea: Determine argument values for which recursive case does not apply Introduce a base case for each one of these

Recursive Program for Combinations 36 n ( ) n ( n) n ( 0) n 1 n 1 = + r 1, n > r > 0 = 1 = 1 r ( r ) ( ) static int combs(int n, int r) { //assume n>=r>=0 if (r == 0 r == n) return 1; //base cases else return combs(n-1,r) + combs(n-1,r-1); }

Exercise for the reader (you!) 37 Modify our recursive program so that it caches results Same idea as for our caching version of the fibonacci series Question to ponder: When is it worthwhile to adding caching to a recursive function? Certainly not always Must think about tradeoffs: space to maintain the cached results vs speedup obtained by having them

Something to think about 38 With fib(), it was kind of a trick to arrange that: cached[n]=fib(n) Caching combinatorial values will force you to store more than just the answer: Create a class called Triple Design it to have integer fields n, r, v Store Triple objects into ArrayList<Triple> cached; Search cached for a saved value matching n and r Hint: use a foreach loop