Examples of Recursion

Examples of Recursion - Lecture 9: Lecture Examples of...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Lecture 9: Lecture Examples of Recursion Examples PIC 10B Todd Wittman Todd Wittman The Recursion Process A recursive function is a function that calls recursive is upon itself. upon We have to be careful to avoid infinite loops. loops. Each function call should solve a smaller version of the same problem. This is called the recursion step. recursion The process should be driven toward a very simple stopping condition, often called the base case. base 1 Ex: Palindromes A palindrome is a word that is the same backwards and forwards. and eve madam racecar amanaplanacanalpanama eve amanaplanacanalpanama To test for palindrome, we compare 1st & last letter. Then the 2nd & 2nd to last letter. And so on... Then Test with function call: isPalindrome("madam"); isPalindrome("madam Remember booleans are evaluated left to right and a booleans are true/false value is returned as soon as possible. true/false bool isPalindrome (string s) { (string if (s.length() <= 1) return true; if return (s[0]==s[s.length()-1]) 1]) && isPalindrome(s.substr(1,s.length()-2)); && } Ex: Reversing Input Ex What does this function do? What void reverse() { char c; cin >> c; if (c != '\n') { reverse(); cout << c; } return; } The user types in a word then ENTER. It then prints back the word in reverse order. prints 2 Ex: Recurrence Relations Note that we can code up any recurrence relation with recursion. with xN = 5xN-1 - 4xN-2 + 6xN-3, x1=1, x2=2, x3=3 int x (int N) { if (N==1) return 1; if (N==2) return 2; if (N==3) return 3; return 5*x(N-1) - 4*x(N-2) + 6*x(N-3); 1) } Just realize that it's going to be painfully slow. Just Ex: Text Parsing Parsing is the process of dividing a text string into words found in the dictionary. Given a phrase, we want to detect whether it can be parsed into words (true/false) and if so then return the string with spaces inserted. the "dogcatmonkey" true, "dog cat monkey" true, "goodbyeduck" true, "good bye duck" true, "empirestrikeszzzz" false false Assume we have a function that looks up words in the dictionary and returns true if the word is found. the bool isInDictionary(string word); 3 Ex: Text Parsing Our function needs to return two things: true/false if it can be Our parsed and the parsed string. bool canBeParsed(string phrase, string& parsed); bool Is the given phrase a word in the dictionary? Is BASE CASE YES -- return true and parsed = phrase YES NO -- Divide the phrase into two parts at position i=1. NO "catdogmonkey" i=1 firstPart secondPart – Is firstPart a word in the dictionary? Is firstPart YES -- Can secondPart be parsed? RECURSION STEP YES Can secondPart – YES -- return true and parsed = firstPart + " " + parsedSecondPart parsed firstPart parsedSecondPart NO -- Increment position i. NO Increment bool canBeParsed(string phrase, string& parsed) { if (isInDictionary(phrase)) { parsed = phrase; return true; } for (int i=1; i<phrase.length(); i++) { string firstPart = phrase.substr(0,i); string firstPart string secondPart = phrase.substr(i,phrase.length()-i); string secondPart phrase.substr(i,phrase.length() string parsedSecondPart; string parsedSecondPart if (isInDictionary(firstPart) && canBeParsed(secondPart,parsedSecondPart) ) { canBeParsed(secondPart,parsedSecondPart parsed = firstPart + " " + parsedSecondPart; parsed firstPart parsedSecondPart return true; } } return false; } 4 Ex: Permutations A permutation is a re-arrangement of the order of a group of permutation arrangement distinct objects. distinct For N distinct objects, there are N! permutations. For The 2!=2 permutations of A & B: The AB BA The 3!=6 permuations of {1,2,3}: permuations 123 132 213 231 312 321 The 4!=24 permuations of letters of "YODA" permuations To permute 4 things, fix the first item ("Y") and then permute the last 3 things ("ODA") the Now fix the first of the 3 things ("O") and permute the remaining 2 ("DA"). remaining Note there is recursion here. Note Ex: Permutations Sec 14.2: We want to generate a string vector Sec We containing all possible permutations of a given word. containing So we would call our function permute as below. permute int main() { string word; cout << "Enter a word: "; cin >> word; cout<<"The permutations of "<<word<<" are:\n"; vector<string> v = permute(word); vector<string> permute(word for (int i=0; i < v.size(); i++) i=0; v.size cout << v[i] << "\n"; << v[i return 0; } 5 vector<string> permute (string word) { vector<string> result; if (word.length() == 1) { result.push_back(word); return result; } for (int i=0; i<word.length(); i++) { string shorter = word.substr(0,i) string + word.substr(i+1,word.length()-i-1); word.substr(i+1,word.length() vector<string> shortWords = permute(shorter); vector<string> shortWords permute(shorter for (int j=0; j<shortWords.size(); j++) { string longer = word[i]+shortWords[j]; string word[i]+shortWords[j result.push_back(longer); } } return result; } The non-recursive version is given on p. 544. The Application: Anagrams An anagram is a re-arrangement of the letters of An arrangement a phrase into a new phrase. phrase force be with you out obey rich few If we just generate permutations of the original phrase, most permutations will be garbage. phrase, force be with you foberwithcyoue force foberwithcyoue But if we generate all permutations and then parse each permutation, then I think we've got next week's HW assignment. next 6 ...
View Full Document

Ask a homework question - tutors are online