You are on page 1of 6

Lecture 9:

Examples of Recursion
PIC 10B
Todd Wittman

The Recursion Process


A recursive function is a function that calls
upon itself.
 We have to be careful to avoid infinite
loops.
 Each function call should solve a smaller
version of the same problem. This is
called the recursion step.
step.
 The process should be driven toward a
very simple stopping condition, often
called the base case.
case.


Ex: Palindromes
A palindrome is a word that is the same backwards
and forwards.
eve madam racecar amanaplanacanalpanama
 To test for palindrome, we compare 1st & last letter.
Then the 2nd & 2nd to last letter. And so on...
 Test with function call:
isPalindrome("madam");
isPalindrome("madam");
 Remember booleans are evaluated left to right and a
true/false value is returned as soon as possible.
bool isPalindrome (string s) {
if (s.length
() <= 1) return true;
(s.length()
return (s[0]==s[s.length()(s[0]==s[s.length()-1])
&& isPalindrome(s.substr(1,s.length()isPalindrome(s.substr(1,s.length()-2));
}


Ex: Reversing Input




What does this function do?


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.

Ex: Recurrence Relations




Note that we can code up any recurrence relation


with recursion.
xN = 5xN-1 - 4xN-2 + 6xN-3, x1=1, x2=2, x3=3
int x (int
(int N) {
if (N==1) return 1;
if (N==2) return 2;
if (N==3) return 3;
return 5*x(N5*x(N-1) - 4*x(N4*x(N-2) + 6*x(N6*x(N-3);
}
Just realize that it's going to be painfully slow.

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.
"dogcatmonkey"
true, "dog cat monkey"
dogcatmonkey"
"goodbyeduck"
true, "good bye duck"
goodbyeduck"
"empirestrikeszzzz"
false
empirestrikeszzzz"
 Assume we have a function that looks up words in
the dictionary and returns true if the word is found.


bool isInDictionary(string word);

Ex: Text Parsing









Our function needs to return two things: true/false if it can be


parsed and the parsed string.
bool canBeParsed(string phrase, string& parsed);
Is the given phrase a word in the dictionary?
BASE CASE
YES -- return true and parsed = phrase
NO -- Divide the phrase into two parts at position i=1.
"catdogmonkey"
catdogmonkey"
i=1

firstPart
secondPart
Is firstPart a word in the dictionary?
RECURSION STEP
 YES -- Can secondPart be parsed?
YES -- return true and
parsed = firstPart + " " + parsedSecondPart
 NO -- Increment position i.

bool canBeParsed(string phrase, string& parsed) {


if (isInDictionary(phrase
)) {
(isInDictionary(phrase))
parsed = phrase;
return true;
}
for (int
(); i++) {
(int i=1; i<phrase.length
i<phrase.length();
string firstPart = phrase.substr(0,i);
string secondPart = phrase.substr(i,phrase.length()phrase.substr(i,phrase.length()-i);
string parsedSecondPart;
parsedSecondPart;
if (isInDictionary(firstPart
(isInDictionary(firstPart))
&& canBeParsed(secondPart,parsedSecondPart)
canBeParsed(secondPart,parsedSecondPart) ) {
parsed = firstPart + " " + parsedSecondPart;
parsedSecondPart;
return true;
}
}
return false;
}

Ex: Permutations





A permutation is a rere-arrangement of the order of a group of


distinct objects.
For N distinct objects, there are N! permutations.
The 2!=2 permutations of A & B:
AB BA
The 3!=6 permuations of {1,2,3}:
123 132 213 231 312 321
The 4!=24 permuations of letters of "YODA"

To permute 4 things, fix the first item ("Y") and then permute
the last 3 things ("ODA")
Now fix the first of the 3 things ("O") and permute the
remaining 2 ("DA").
Note there is recursion here.

Ex: Permutations
Sec 14.2:
14.2: We want to generate a string vector
containing all possible permutations of a given word.
 So we would call our function permute as below.
int main() {
string word;
cout << "Enter a word: ";
cin >> word;
cout<<"The
cout<<"The permutations of "<<word<<" are:\
are:\n";
vector<string> v = permute(word);
permute(word);
for (int
(int i=0; i < v.size();
v.size(); i++)
cout << v[i]
v[i] << "\
"\n";
return 0;
}


vector<string> permute (string word) {


vector<string> result;
if (word.length
() == 1) {
(word.length()
result.push_back(word);
result.push_back(word);
return result;
}
for (int
(); i++) {
(int i=0; i<word.length
i<word.length();
string shorter = word.substr(0,i)
+ word.substr(i+1,word.length()word.substr(i+1,word.length()-i-1);
vector<string> shortWords = permute(shorter);
permute(shorter);
for (int
(); j++) {
(int j=0; j<shortWords.size
j<shortWords.size();
string longer = word[i]+shortWords[j];
word[i]+shortWords[j];
result.push_back(longer);
result.push_back(longer);
}
}
return result;
}
 The nonnon-recursive version is given on p. 544.

Application: Anagrams


An anagram is a rere-arrangement of the letters of


a phrase into a new phrase.
force be with you
out obey rich few

If we just generate permutations of the original


phrase, most permutations will be garbage.
force be with you
foberwithcyoue

But if we generate all permutations and then


parse each permutation, then I think we've got
next week's HW assignment.

You might also like