Repetition via Recursion

advertisement
Lecture 13
Recursion part 2
Richard Gesick
Advanced Recursion
• Sometimes recursion involves processing a
collection.
• While it could be done using 'foreach' or some
other iterative approach, recall that recursion
works best for non-linear structures.
• Recursion is also useful for making use of the
activation stack as a "reminder" of where we've
been and what remains to be done.
multiple recursion
Consider this example: what is DoWork(5) ?
void DoWork(int i)
{
Console.WriteLine(i);
if (i > 2)
{
DoWork(i-1);
DoWork(i-2);
}
Console.WriteLine(i);
}
multiple recursion (2)
• Fibonacci series: an= a(n-1) +a(n-2) i.e. the
next number in the series is the sum of the
2 preceding numbers.
• the Fibonacci series: 1,1,2,3,5,8,13,…
• Write a multiply recursive method:
int Fibo ( int n)
{
}
• (Remember stopping state first!)
The solution
int Fib(int i)
{
if (i < 2)
return 1;
else
return Fib(i-1) + Fib(i-2);
}
String Processing
How can we reverse a string recursively?
Pseudo-code solution
(base case is when string is ? ):
reverse a string by repeatedly
removing the first character,
reversing this substring (recursively),
appending the first character to the end
string reversal code
static string Reverse (string s)
{
if (s.Length==1)
return s;
else
return Reverse(s.Substring(1)) + s[0];
}
Non-linear Recursion
• Folders and files within a computer system
are an excellent example of a non-linear
structure that is easily processed via
recursion.
• This is also possible using iteration, but we
would have more coding work to do in
handling where we've been in the file
system.
• We can leverage the activation stack to
remember for us.
Non-linear Recursion
• Consider the steps to count the total number of files:
If we're in a folder with no files (or subfolders),
then we return 0
Otherwise, we return the count of the files in the
folder + all the files in the subfolders
• It's the second part that's tricky... but notice that's
where the recursive call comes in. We just need to
recursively call for each subfolder (so this is
recursion wrapped inside of iteration):
solution
private int CountFiles(DirectoryInfo di)
{
int file_count = 0;
file_count += di.GetFiles().Length;
foreach (DirectoryInfo sub_folder in di.GetDirectories())
file_count += CountFiles(sub_folder);
return file_count;
}
Download