Recursion - Object-Oriented Programming and Data Structures - Lecture Sl, Lecture notes of Object Oriented Programming

Major points from this lecture are: Recursion, Recursion as a Math Technique, Sum the Digits in a Number, Palindrome, Factorial Function, Permutations, Recursive Program, General Approach, Writing Recursive, Cautionary Note . Object-Oriented Programming and Data Structures course includes program structure and organization, object oriented programming, graphical user interfaces, algorithm analysis, recursion, data structures (lists, trees, stacks, queues, heaps, search trees, hash tables, graphs

Typology: Lecture notes

2012/2013

Uploaded on 08/20/2013

yumni
yumni 🇮🇳

5

(2)

25 documents

1 / 37

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Recursion
Arisesinthreeformsincomputerscience
Recursionasamathematicaltoolfordefiningafunction
intermsofitsownvalueinasimplercase
Recursionasaprogrammingtool.Youveseenthis
previouslybutwe’lltakeittomindbendingextremes
(bytheendoftheclassitwillseemeasy!)
Recursionusedtoprovepropertiesaboutalgorithms.
Weusetheterminductionforthisandwilldiscussit
later.
docsity.com
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25

Partial preview of the text

Download Recursion - Object-Oriented Programming and Data Structures - Lecture Sl and more Lecture notes Object Oriented Programming in PDF only on Docsity!

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.

Recursion

as

a

math

technique

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:

Is

a

string

a

palindrome?

isPalindrome(“racecar”)

true - isPalindrome(“pumpkin”) = false /** = "s is a palindrome" */ public static boolean isPalindrome(String s) { if (s.length() <= 1) return true; // s has at least 2 charsint n= s.length()-1;return s.charAt(0) == s.charAt(n) && isPalindrome(s.substring(1, n)); } r a c e c a r a c e c a c e c e Substring from char(1) to char(n-1)

Count

the

e’s

in

a

string

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 fromchar(1) to end

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

Permutations of

  • Total number = 4·3! = 4·6 = 24: 4! Permutations ofnon-orange blocks Each permutation of the three non-orange blocks gives four permutationswhen the orange block is included

A

Recursive

Program

static int fact(int n) { if (n = = 0) return 1; else return nfact(n-1); }* 0! = 1n! = n·(n  1)!, n > 0 6 2 1 1 Execution of fact(4) fact(4)fact(3)fact(2)fact(1)fact(0) 24

General

Approach

to

Writing

Recursive

Functions

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 ‐

in our factorial example)

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

The

Fibonacci

Function

Mathematical definition: fib(0) = 0 fib(1) = 1 fib(n) = fib(n1) + fib(n2), n 2 - 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); } two base cases! Fibonacci (LeonardoPisano) 1170  1240? Statue in Pisa, ItalyGiovanni Paganucci 1863

Recursive

Execution

**static int fib(int n) { if (n ==

return 0; else if (n ==

return 1; else return fib(n-2)

fib(n-1); } fib(4) fib(2) fib(0) fib(1) Execution of fib(4): 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, 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

Adding

Memoization

to

our

solution

Before:

After static int fib(int n) { if (n == 0) return 0; else if (n == 1) return 1; else return fib(n-2) + fib(n-1); **} static ArrayList cached = new ArrayList(); static int fib(int n) { if(n < cached.size()) return cached.get(n); int v; if (n ==

v

0; else if (n ==

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; }**

Why

did

it

work?

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 1 1 2 3 cached@BA8900, size= cached.get(0)= cached.get(1)= … cached.get(n)=fib(n) Property of our code: cached.get(n) accessed after fib(n) computed

Positive

Integer

Powers

a n

a

a

a

a (n times)

Alternate description: - a 0 = 1

a n+ = a ∙ a n static int power(int a, int n) { if (n == 0) return 1;else return apower(a,n-1); }*