Upload
silas-grant
View
232
Download
2
Embed Size (px)
Citation preview
RecursionRecursion
Circular DefinitionCircular Definition
Circular definitionCircular definition Dialectic materialism Dialectic materialism is materialism that is is materialism that is
dialectic.dialectic. Uses the term being used as part of the definitionUses the term being used as part of the definition Not helpfulNot helpful
Recursive DefinitionRecursive Definition
Recursive DefinitionRecursive Definition Uses the term being defined as part of the Uses the term being defined as part of the
definitiondefinition Is Is notnot a circular definition a circular definition
Factorial of n (n!)Factorial of n (n!)
n! = 1, when n = 0n! = 1, when n = 0n! = n (n – 1)!, when n > 0n! = n (n – 1)!, when n > 0
Recursive FunctionRecursive Function Recursive functionRecursive function
Is an example of divide-and-conquor techniqueIs an example of divide-and-conquor technique Invokes itself within the functionInvokes itself within the function Muse contain a Muse contain a basebase case case
Recursive Recursive factorialfactorial function function
int fact(int n){int fact(int n){ if (n == 0) if (n == 0) return 1; return 1; else else return n * fact(n – 1); return n * fact(n – 1);}}
Invocation
cout << fact(4);
Recursive Recursive Factorial Factorial FunctionFunction
fact(4) return 4 * fact(3)
fact(3) return 3 * fact(2)
fact(2) return 2 * fact(1)
fact(1) return 1 * fact(0)
fact(0) return 1
fact(1) return 1 * 1
fact(2) return 2 * 1
fact(3) return 3 * 2
fact(4) return 4 * 3
Fibonnaci NumberFibonnaci Number
fib(n) = 1, when n = 0fib(n) = 1, when n = 0fib(n) = 1, when n = 1fib(n) = 1, when n = 1fib(n) = fib(n -1) + fib(n – 2), when n > 1fib(n) = fib(n -1) + fib(n – 2), when n > 1
Fibonacci FunctionFibonacci Function
int fib(int n){int fib(int n){ if (n == 0 || n == 1) if (n == 0 || n == 1) return 1; return 1; else else return fib(n – 1) + fib(n – 2); return fib(n – 1) + fib(n – 2);}}
To Write a Successful To Write a Successful Recursive FunctionRecursive Function
Identify the non-recursive case (which is usually a trivial Identify the non-recursive case (which is usually a trivial case).case).
Identify the recursive case (which calls itself).Identify the recursive case (which calls itself). The recursive call must “reduce” the data size, so that the The recursive call must “reduce” the data size, so that the
non-recursive case it reached eventuallynon-recursive case it reached eventually
Factorial FunctionFactorial Function
int fact(int nn){int fact(int nn){ if (n == 0) if (n == 0) return 1; return 1; else else return n * fact(n – 1); return n * fact(n – 1);}}
Your TurnYour Turn
Write a recursive function Write a recursive function sumOf(int n), sumOf(int n), which returns the sum of consecutive integers which returns the sum of consecutive integers between 1 and n.between 1 and n.
E.g., cout << sumOf(10); // prints 55.E.g., cout << sumOf(10); // prints 55.
SolutionSolution
int sumOf(int n){ if (n == 1) { return 1; } else { return n + sumOf(n - 1); }}
Your TurnYour Turn
Write a recursive function Write a recursive function power(double b, int x), power(double b, int x), which returns b^xwhich returns b^x(b raised to the power of x).(b raised to the power of x).
E.g., cout << power(2, 8) prints 256E.g., cout << power(2, 8) prints 256
SolutionSolutionint power(double b, int x){ double result; if (x == 0){ result = 1; } else if (x == 1){ result = b; } else { result = b * power(b, x – 1); } return result; }
Your TurnYour Turn
Write a recursive function Write a recursive function which reads a series of characters from the which reads a series of characters from the console and prints them backwordsconsole and prints them backwords. (A . (A sentinel value of ‘z’ signals the end of input.) sentinel value of ‘z’ signals the end of input.)
E.g., main() can contain the following:E.g., main() can contain the following:
int main() {int main() { cout << “Enter a series of chars.\n”; cout << “Enter a series of chars.\n”; printBackwards(); printBackwards(); … …}}
SolutionSolutionvoid printBackward() { char ch; cin >> ch; if (ch != 'z') { printBackward(); cout << ch; }}
Your TurnYour Turn Write a recursive function named Write a recursive function named
minimum(int a[], int count) minimum(int a[], int count) which returns the which returns the minimum value of an int array.minimum value of an int array.
E.g., main() can contain the following:E.g., main() can contain the following:
int main() {int main() { int a[]; int a[]; int count; int count; intializeArray(a, count); intializeArray(a, count); cout << “Min: “ << minimum(a, count); cout << “Min: “ << minimum(a, count); … …}}
SolutionSolutionint minimum(int a[], int count) { int min = a[count - 1]; if (count == 1) { return min; } else { if (min < minimum(a, count - 1)) return min; else return minimum(a, count - 1); }}
Your TurnYour Turn
Write a recursive function named Write a recursive function named greatestCommonFactor(int a, int b)greatestCommonFactor(int a, int b)which returns the greatest common facterwhich returns the greatest common facterbetween positive integers between positive integers aa and and bb..
GCF can be found from the following rules:GCF can be found from the following rules:
if b = 0, then GCF is a; otherwise, it is if b = 0, then GCF is a; otherwise, it is the GCF of b and (a mod b).the GCF of b and (a mod b).
SolutionSolutionint greatestCommonFactor(int a, int b){ if (b == 0) return a; else return lowestCommonFactor(b, a % b);}
Your TurnYour Turn
Using recursion, write a function that deletes a Using recursion, write a function that deletes a particular item from an ordered list, particular item from an ordered list, implemented as a linked list.implemented as a linked list.
void delete (Node* &head,void delete (Node* &head, elemType item); elemType item);
2 4 5 7head Ω
item 5
SolutionSolutionvoid delete (Node* &head, elemType item){ Node* temp = head; if (temp->getData() == item) { head = head->getNext(); delete temp; count--; } else { delete (head->getNext(), item); }}
Your TurnYour Turn
Using recursion, write a boolean function Using recursion, write a boolean function which checks if an item is in a linked list.which checks if an item is in a linked list.
bool search(Node* start,bool search(Node* start, elemType item); elemType item);
2 4 5 7head Ω
item 5
SolutionSolutionbool search(Node* start, elemType item){ if (start == NULL) return false; else if (start->getData() == item) return true; else return search(start->getNext(), item);}
Tower of HanoiTower of Hanoi
• Stack of 64 golden disks, with the largest at the bottom and progressively smaller ones above.
• When the stack is completely moved, the world will come to an end.
• It would take 264−1 (18,446,744,073,709,551,615) moves to finish. At a rate of one move per sec, it would take them roughly 585 billion years to finish.
Towers of HanoiTowers of Hanoi
ObjectiveMove the stack of disks from one tower to another with the following rules:•Only one disk may be moved at a time.•Each move consists of taking the upper disk from one of the rods and sliding it onto another rod, on top of the other disks that may already be present on that rod.•No disk may be placed on top of a smaller disk.
SolutionSolution
N disks
Tower 2Tower 1 Tower 3
Move N – 1 disks from 1 to 2
Move 1 disk from 1 to 3
Demo
DemonstrationsDemonstrations
Solution by Hand (Slow Version)Solution by Hand (Slow Version) Solution by RobotSolution by Robot Solution by 5-year oldSolution by 5-year old Manual Solution (Faster VersionManual Solution (Faster Version
Algorithm (n = 3)Algorithm (n = 3)
SolutionSolution
N disks
Tower 2Tower 1 Tower 3
Move N – 1 disks from 1 to 2
Move 1 disk from 1 to 3
Demo
AlgorithmAlgorithm
Move (int n, int from, int to, int aux)Move (int n, int from, int to, int aux) If (n = 1) Then If (n = 1) Then cout << “Move disk from “ cout << “Move disk from “ << from << “ to “ << to << endl << from << “ to “ << to << endl Else Else Move (n – 1, from, aux, to) Move (n – 1, from, aux, to) cout << “Move disk from “ cout << “Move disk from “ << from << “ to << to << endl; << from << “ to << to << endl; Move (n – 1, aux, to, from) Move (n – 1, aux, to, from) End If End If