Recursion2.pptx

advertisement
What we will do today
1. You’ll try to write a recursive function to solve a
simple problem
2. We’ll return to the count number of “a”s example
from the previous day, and I’ll explore it a bit more
3. I’ll discuss an alternative recursive string function
4. I’ll discuss the “natural” recursive structure of files
and directories, and go through a example with that
5. You will also write a recursive function with files and
directories
6. If we have time: even more practice with recursive
functions
First Recursion Problem
•
•
•
•
Go to http://codingbat.com/java/Recursion-1
Solve count7
If you finish, solve bunnyEars2
If you finish, do fibonacci (this one is so old
that I solved in my very first CS class…and it
was pretty dang old then)
• If you finish, do a tiny green dance in your
chair and then move on to some more
public int countAs(String input) {
if(input.isEmpty())
return 0;
String restOfString = input.substring(1);
int restOfStringCount = countAs(restOfString);
if(input.charAt(0) == 'a') {
return restOfStringCount + 1;
} else {
return restOfStringCount;
}
}
A genuinely good example of recursion
How would you find the largest file within a directory (oh,
and this directory can contain other directories)
Download