Docsity

Recursion: A Powerful Technique for Functions and Programs, Slides of Object Oriented Programming

Partial preview of the text

Download Recursion: A Powerful Technique for Functions and Programs and more Slides Object Oriented Programming in PDF only on Docsity!

Recursion

Recursion

  • 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.

Example: Sum the digits in a number

  • E.g. sum(87012) = 2+(1+(0+(7+8))) = 18 /** return sum of digits in n, given 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?

  • 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)); } r a c e c a r a c e c a c e c e Substring from s[1] to s[n-1]

The Factorial Function (n!)

  • Define n! = n·(n- 1 )·(n- 2 )···3·2· 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

The Factorial Function (n!)

  • 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)!

Observation

  • 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

/** = n!, for n >= 0 / static int fact( int n) { if (n = = 0) return 1; // { n > 0 } return nfact(n-1); }

n! = n·(n- 1 )!, n > 0 1

Execution of fact(4) fact(1) fact(4) fact(3) fact(0) fact(2)

A cautionary note

  • 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!

The Fibonacci Function

  • 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), for 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) 1170 - 1240? Statue in Pisa, Italy Giovanni Paganucci 1863

One thing to notice

  • 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(1) fib(2)

Memoization (fancy term for “caching”)

  • 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, 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

/** 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 This appends v to cached, keeping cached’s definition true

Notice the development process

  • 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