Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 13 Recursion part 2 Richard Gesick. Advanced Recursion Sometimes recursion involves processing a collection. While it could be done using 'foreach'

Similar presentations


Presentation on theme: "Lecture 13 Recursion part 2 Richard Gesick. Advanced Recursion Sometimes recursion involves processing a collection. While it could be done using 'foreach'"— Presentation transcript:

1 Lecture 13 Recursion part 2 Richard Gesick

2 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.

3 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); }

4 multiple recursion (2) Fibonacci series: a n = 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!)

5 The solution int Fib(int i) { if (i < 2) return 1; else return Fib(i-1) + Fib(i-2); }

6 String Processing How can we reverse a string recursively?

7 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

8 string reversal code static string Reverse (string s) { if (s.Length==1) return s; else return Reverse(s.Substring(1)) + s[0]; }

9 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.

10 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):

11 solution private int CountFiles(DirectoryInfo di) { int file_count = 0; file_count += di.GetFiles().Length; foreach (DirectoryInfo sub_folder indi.GetDirectories()) file_count += CountFiles(sub_folder); return file_count; }


Download ppt "Lecture 13 Recursion part 2 Richard Gesick. Advanced Recursion Sometimes recursion involves processing a collection. While it could be done using 'foreach'"

Similar presentations


Ads by Google