Example: Is a string a palindrome? Recursion. Count the e s in a string. Recursion as a math technique 12/02/2013. Example: Sum the digits in a number

Similar documents
SECTION 1.5 : SUMMATION NOTATION + WORK WITH SEQUENCES

Example 2 Find the square root of 0. The only square root of 0 is 0 (since 0 is not positive or negative, so those choices don t exist here).

BINOMIAL EXPANSIONS In this section. Some Examples. Obtaining the Coefficients

Infinite Sequences and Series

THE ARITHMETIC OF INTEGERS. - multiplication, exponentiation, division, addition, and subtraction

Soving Recurrence Relations

In nite Sequences. Dr. Philippe B. Laval Kennesaw State University. October 9, 2008

Lecture 4: Cauchy sequences, Bolzano-Weierstrass, and the Squeeze theorem

How To Solve The Homewor Problem Beautifully

1. MATHEMATICAL INDUCTION

CS103A Handout 23 Winter 2002 February 22, 2002 Solving Recurrence Relations

Sequences and Series

CS103X: Discrete Structures Homework 4 Solutions

Trigonometric Form of a Complex Number. The Complex Plane. axis. ( 2, 1) or 2 i FIGURE The absolute value of the complex number z a bi is

5 Boolean Decision Trees (February 11)

Department of Computer Science, University of Otago

5.3. Generalized Permutations and Combinations

Repeating Decimals are decimal numbers that have number(s) after the decimal point that repeat in a pattern.

Discrete Mathematics and Probability Theory Spring 2014 Anant Sahai Note 13

Here are a couple of warnings to my students who may be here to get a copy of what happened on a day that you missed.

A Recursive Formula for Moments of a Binomial Distribution

Incremental calculation of weighted mean and variance

A probabilistic proof of a binomial identity

Factoring x n 1: cyclotomic and Aurifeuillian polynomials Paul Garrett <garrett@math.umn.edu>

3. Greatest Common Divisor - Least Common Multiple

Basic Elements of Arithmetic Sequences and Series

Determining the sample size

A Secure Implementation of Java Inner Classes

Notes on exponential generating functions and structures.

Running Time ( 3.1) Analysis of Algorithms. Experimental Studies ( 3.1.1) Limitations of Experiments. Pseudocode ( 3.1.2) Theoretical Analysis

Project Deliverables. CS 361, Lecture 28. Outline. Project Deliverables. Administrative. Project Comments

Solutions to Exercises Chapter 4: Recurrence relations and generating functions

CHAPTER 3 THE TIME VALUE OF MONEY

THE REGRESSION MODEL IN MATRIX FORM. For simple linear regression, meaning one predictor, the model is. for i = 1, 2, 3,, n

Lesson 15 ANOVA (analysis of variance)

.04. This means $1000 is multiplied by 1.02 five times, once for each of the remaining sixmonth

Building Blocks Problem Related to Harmonic Series

Time Value of Money. First some technical stuff. HP10B II users

Permutations, the Parity Theorem, and Determinants

SAMPLE QUESTIONS FOR FINAL EXAM. (1) (2) (3) (4) Find the following using the definition of the Riemann integral: (2x + 1)dx

Present Value Factor To bring one dollar in the future back to present, one uses the Present Value Factor (PVF): Concept 9: Present Value

Listing terms of a finite sequence List all of the terms of each finite sequence. a) a n n 2 for 1 n 5 1 b) a n for 1 n 4 n 2

*The most important feature of MRP as compared with ordinary inventory control analysis is its time phasing feature.

Asymptotic Growth of Functions

Math C067 Sampling Distributions

Chapter 5: Inner Product Spaces

S. Tanny MAT 344 Spring be the minimum number of moves required.

Chatpun Khamyat Department of Industrial Engineering, Kasetsart University, Bangkok, Thailand

Section 8.3 : De Moivre s Theorem and Applications

7.1 Finding Rational Solutions of Polynomial Equations

Elementary Theory of Russian Roulette

The Power of Free Branching in a General Model of Backtracking and Dynamic Programming Algorithms

FIBONACCI NUMBERS: AN APPLICATION OF LINEAR ALGEBRA. 1. Powers of a matrix

Chapter 14 Nonparametric Statistics

The new assembly line of the Car Corp.

Convexity, Inequalities, and Norms

2-3 The Remainder and Factor Theorems

Lesson 17 Pearson s Correlation Coefficient

Quantitative Computer Architecture

FM4 CREDIT AND BORROWING

Properties of MLE: consistency, asymptotic normality. Fisher information.

Sequences and Series Using the TI-89 Calculator

Multiplexers and Demultiplexers

hp calculators HP 12C Statistics - average and standard deviation Average and standard deviation concepts HP12C average and standard deviation

Math 114- Intermediate Algebra Integral Exponents & Fractional Exponents (10 )

Week 3 Conditional probabilities, Bayes formula, WEEK 3 page 1 Expected value of a random variable

1. C. The formula for the confidence interval for a population mean is: x t, which was

How to set up your GMC Online account

WHEN IS THE (CO)SINE OF A RATIONAL ANGLE EQUAL TO A RATIONAL NUMBER?

Notes on Combinatorics. Peter J. Cameron

Static revisited. Odds and ends. Static methods. Static methods 5/2/16. Some features of Java we haven t discussed

Factors of sums of powers of binomial coefficients

Review: Classification Outline

Cooley-Tukey. Tukey FFT Algorithms. FFT Algorithms. Cooley

CHAPTER 11 Financial mathematics

Simple Annuities Present Value.

Concept: Types of algorithms

Desktop Management. Desktop Management Tools

SEQUENCES AND SERIES

Lecture 3. denote the orthogonal complement of S k. Then. 1 x S k. n. 2 x T Ax = ( ) λ x. with x = 1, we have. i = λ k x 2 = λ k.

The Stable Marriage Problem

CME 302: NUMERICAL LINEAR ALGEBRA FALL 2005/06 LECTURE 8

I. Why is there a time value to money (TVM)?

Agenda. Outsourcing and Globalization in Software Development. Outsourcing. Outsourcing here to stay. Outsourcing Alternatives

Definition. A variable X that takes on values X 1, X 2, X 3,...X k with respective frequencies f 1, f 2, f 3,...f k has mean

Fast Fourier Transform

Domain 1: Designing a SQL Server Instance and a Database Solution


Hypergeometric Distributions

1 Computing the Standard Deviation of Sample Means

CHAPTER 7: Central Limit Theorem: CLT for Averages (Means)

Chapter 7: Confidence Interval and Sample Size

Output Analysis (2, Chapters 10 &11 Law)

Section 11.3: The Integral Test

5.4 Amortization. Question 1: How do you find the present value of an annuity? Question 2: How is a loan amortized?

CS100: Introduction to Computer Science

Laws of Exponents Learning Strategies

Math 113 HW #11 Solutions

Transcription:

Example: Sum the digits i a umber /** retur sum of digits i, give >= 0 */ public static it sum(it ) { if ( < 0) retur ; sum calls itself! // has at least two digits: // retur first digit + sum of rest retur %0 + sum(/0); Lecture 6 CS0 Sprig 03 RECURSION E.g. sum(870) = +(+(0+(7+8))) 8 Recursio Arises i three forms i computer sciece Recursio as a mathematical tool for defiig a fuctio i terms of its ow value i a simpler case Recursio as a programmig tool. You ve see this previously but we ll take it to mid-bedig extremes (by the ed of the class it will seem easy!) 5 Example: Is a strig a palidrome? /** = "s is a palidrome" */ public static boolea ispalidrome(strig s) { if (s.legth() <) retur true; Substrig from char() to char(-) // s has at least chars it = s.legth()-; retur s.charat(0) == s.charat() && ispalidrome(s.substrig(, )); Recursio used to prove properties about algorithms. We use the term iductio for this ad will discuss it later. ispalidrome( racecar ) = true ispalidrome( pumpki ) = false r a c e c a r a c e c a c e c e 3 Recursio as a math techique Broadly, recursio is a powerful techique for specifyig fuctios, sets, ad programs A few recursively-defied fuctios ad programs factorial combiatios expoetiatio (raisig to a iteger power) Some recursively-defied sets grammars expressios data structures (lists, trees,...) 6 Cout the e s i a strig /** = " umber of times c occurs i s */ public static it coutem(char c, Strig s) { if (s.legth() == 0) retur 0; // { s has at least character if (s.charat(0)!= c) retur coutem(c, s.substrig()); // { first character of s is c retur + coutem (c, s.substrig()); coutem( e, it is easy to see that this has may e s ) = coutem( e, Mississippi ) = 0 Substrig from char() to ed

The Factorial Fuctio (!) Observatio 7 0 Defie! = () () 3 read: factorial E.g., 3! = 3 = 6 By covetio, 0! The fuctio it it that gives! o iput is called the factorial fuctio Oe way to thik about the task of permutig the four colored blocks was to start by computig all permutatios of three blocks, the fidig all ways to add a fourth block Ad this explais why the umber of permutatios turs out to be! Ca geeralize to prove that the umber of permutatios of blocks is! The Factorial Fuctio (!) A Recursive Program 8! is the umber of permutatios of distict objects There is just oe permutatio of oe object.! There are two permutatios of two objects:! = There are six permutatios of three objects: 3! = 6 3 3 3 3 3 3 If > 0,! = ( )! 0!! = ()!, > 0 static it fact(it ) { if ( = = 0) retur ; else retur *fact(-); Executio of fact() fact() fact(3) fact() fact() fact(0) 6 Permutatios of Geeral Approach to Writig Recursive Fuctios 9 Permutatios of o-orage blocks. Try to fid a parameter, say, such that the solutio for ca be obtaied by combiig solutios to the same problem usig smaller values of (e.g., (-) i our factorial example). Fid base case(s) small values of for which you ca just write dow the solutio (e.g., 0! ) Each permutatio of the three oorage blocks gives four permutatios whe the orage block is icluded 3. Verify that, for ay valid value of, applyig the reductio of step repeatedly will ultimately hit oe of the base cases Total umber = 3! = 6 = :!

3 A cautioary ote Keep i mid that each istace of your recursive fuctio has its ow local variables Also, remember that higher istaces are waitig while lower istaces ru Not such a good idea to touch global variables from withi recursive fuctios Legal but a commo source of errors Must have a really clear metal picture of how recursio is performed to get this right! 6 Oe thig to otice This way of computig the Fiboacci fuctio is elegat, but iefficiet It recomputes aswers agai ad agai! To improve speed, eed to save kow aswers i a table! fib() Oe etry per aswer fib() fib(3) Such a table is called a cache fib(0) fib() fib() fib() fib(0) fib() The Fiboacci Fuctio Memoizatio (facy term for cachig ) Mathematical defiitio: fib(0) = 0 two base cases! fib() fib() = fib( ) + fib( ), Fiboacci sequece: 0,,,, 3, 5, 8, 3, static it fib(it ) { if ( == 0) retur 0; else if ( =) retur ; else retur fib(-) + fib(-); Fiboacci (Leoardo Pisao) 700? Statue i Pisa, Italy Giovai Pagaucci 863 7 Memoizatio is a optimizatio techique used to speed up computer programs by havig fuctio calls avoid repeatig the calculatio of results for previously processed iputs. The first time the fuctio is called, we save result The ext time, we ca look the result up Assumes a side effect free fuctio: The fuctio just computes the result, it does t chage thigs If the fuctio depeds o aythig that chages, must empty the saved results list 5 Recursive Executio static it fib(it ) { if ( == 0) retur 0; else if ( =) retur ; else retur fib(-) + fib(-); Executio of fib(): fib(0) fib() fib() fib() fib() fib(3) fib(0) fib() fib() 8 Addig Memoizatio to our solutio Before: After static ArrayList<Iteger> cached = ew ArrayList<Iteger>(); static it fib(it ) { if ( == 0) static it fib(it ) { retur 0; if( < cached.size()) else if ( =) retur cached.get(); retur ; it v; else if ( == 0) retur fib(-) + fib(-); v = 0; else if ( =) v ; else v = fib(-) + fib(-); // cached[] = fib(). This code makes use of the fact // that a ArrayList adds elemets to the ed of the list if( == cached.size()) cached.add(v); retur v; 3

9 Notice the developmet process We started with the idea of recursio Created a very simple recursive procedure Noticed it will be slow, because it wastefully recomputes the same thig agai ad agai So made it a bit more complex but gaied a lot of speed i doig so This is a commo software egieerig patter A Smarter Versio Power computatio: a0 If is ozero ad eve, a = (a/) If is odd, a = a (a/) Java ote: If x ad y are itegers, x/y returs the iteger part of the quotiet Example: a5 = a (a5/) = a (a) = a ((a/)) = a (a) Note: this requires 3 multiplicatios rather tha 5! Why did it work? A Smarter Versio 0 This cached list works because for each value of, either cached.get() is still udefied, or has fib() Takes advatage of the fact that a ArrayList adds elemets at the ed, ad idexes from 0 cached@ba8900, size=5 0 3 cached.get(0)=0 cached.get()= cached.get()=fib() Property of our code: cached.get() accessed after fib() computed 3 Example: a5 = a (a5/) = a (a) = a ((a/)) = a (a) Note: this requires 3 multiplicatios rather tha 5! What if were larger? Savigs would be more sigificat This is much faster tha the straightforward computatio Straightforward computatio: multiplicatios Smarter computatio: log() multiplicatios Positive Iteger Powers a = a a a a ( times) Alterate descriptio: a 0 a + = a a static it power(it a, it ) { if ( == 0) retur ; else retur a*power(a,-); Smarter Versio i Java = 0: a 0 ozero ad eve: a = (a / ) ozero ad odd: a = a (a / ) local variable parameters static it power(it a, it ) { if ( == 0) retur ; it halfpower = power(a,/); if (% == 0) retur halfpower*halfpower; retur halfpower*halfpower*a; The method has two parameters ad a local variable Why are t these overwritte o recursive calls?

How Java compiles recursive code Example: power(, 5) 5 Key idea: Java uses a stack to remember parameters ad local variables across recursive calls Each method ivocatio gets its ow stack frame A stack frame cotais storage for Local variables of method Parameters of method Retur ifo (retur address ad retur value) Perhaps other bookkeepig ifo 8 hp: short for halfpower ( = ) 5 ( = ) ( = ) 5 ( = ) ( = ) ( = ) 5 (retval = ) (hp = ) ( = ) ( = ) ( = ) 5 (retval = ) (hp = ) ( = ) ( = ) 5 (retval = ) (hp = ) ( = ) 5 (retval = ) 3 6 Stacks 9 How Do We Keep Track? stack grows top elemet d elemet 3rd elemet...... bottom elemet top-of-stack poiter Like a stack of dier plates You ca push data o top or pop data off the top i a LIFO (last-i-first-out) fashio A queue is similar, except it is FIFO (first-i-first-out) May frames may exist, but computatio is oly occurrig i the top frame The oes below it are waitig for results The hardware has ice support for this way of implemetig fuctio calls, ad recursio is just a kid of fuctio call 7 Stack Frame A ew stack frame is pushed with each recursive call The stack frame is popped whe the method returs Leavig a retur value (if there is oe) o top of the stack a stack frame halfpower local variables a, parameters retval 30 Coclusio Recursio is a coveiet ad powerful way to defie fuctios Problems that seem isurmoutable ca ofte be solved i a divide-ad-coquer fashio: Reduce a big problem to smaller problems of the same kid, solve the smaller problems Recombie the solutios to smaller problems to form solutio for big problem Importat applicatio (ext lecture): parsig 5

3 Extra slides 3 Biomial Coefficiets For use if we have time for oe more example of recursio This builds o the ideas i the Fiboacci example Combiatios are also called biomial coefficiets because they appear as coefficiets i the expasio of the biomial power (x+y) : (x + y) = x + x y + x y ( 0 ) ( ) + + ( ) y = ( i ) x i y i i= 0 3 Combiatios (a.k.a. Biomial Coefficiets) Combiatios Have Two Base Cases 3 How may ways ca you choose r items from a set of distict elemets? ( ) choose r r 5 ( ) = umber of -elemet subsets of {A,B,C,D,E -elemet subsets cotaiig A: {A,B, {A,C, {A,D, {A,E ( ) -elemet subsets ot cotaiig A: {B,C,{B,D,{B,E,{C,D,{C,E,{D,E Therefore, 5 = + ( ) i perfect form to write a recursive fuctio! 35 ( r ) = ( r ) + ( r ), > r > 0 ( ) Two base cases Comig up with right base cases ca be tricky! Geeral idea: Determie argumet values for which recursive case does ot apply Itroduce a base case for each oe of these 33 Combiatios ( r ) = ( r ) + ( r ), > r > 0 ( ) 0 ( ) ( ) 3 3 3 3 ( ) ( 3) ( ) ( 3) Ca also show that ( r ) = ( ) Pascal s triagle =! r!(r)! 3 3 6 36 Recursive Program for Combiatios ( r ) = ( r ) + ( r ), > r > 0 ( ) static it combs(it, it r) { //assume >=r>=0 if (r == 0 r == ) retur ; //base cases else retur combs(-,r) + combs(-,r-); 6

Exercise for the reader (you!) 37 Modify our recursive program so that it caches results Same idea as for our cachig versio of the fiboacci series Questio to poder: Whe is it worthwhile to addig cachig to a recursive fuctio? Certaily ot always Must thik about tradeoffs: space to maitai the cached results vs speedup obtaied by havig them Somethig to thik about 38 With fib(), it was kid of a trick to arrage that: cached[]=fib() Cachig combiatorial values will force you to store more tha just the aswer: Create a class called Triple Desig it to have iteger fields, r, v Store Triple objects ito ArrayList<Triple> cached; Search cached for a saved value matchig ad r Hit: use a foreach loop 7