The Power of Calling a Method from Itself Svetlin Nakov Telerik Corporation www.telerik.com.

Slides:



Advertisements
Similar presentations
Solve problems with Java code Algorithms with Java.
Advertisements

Towers of Hanoi Move n (4) disks from pole A to pole C such that a disk is never put on a smaller disk A BC ABC.
Chapter 17 Recursion.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 7: Recursion Java Software Structures: Designing and Using.
Recursion. Recursion is a powerful technique for thinking about a process It can be used to simulate a loop, or for many other kinds of applications In.
Recursive methods. Recursion A recursive method is a method that contains a call to itself Often used as an alternative to iteration when iteration is.
Computer Science II Recursion Professor: Evan Korth New York University.
Lesson 19 Recursion CS1 -- John Cole1. Recursion 1. (n) The act of cursing again. 2. see recursion 3. The concept of functions which can call themselves.
Unit 181 Recursion Definition Recursive Methods Example 1 How does Recursion work? Example 2 Problems with Recursion Infinite Recursion Exercises.
Monday, 12/9/02, Slide #1 CS 106 Intro to CS 1 Monday, 12/9/02  QUESTIONS??  On HW #5 (Due 5 pm today)  Today:  Recursive functions  Reading: Chapter.
Recursion Road Map Introduction to Recursion Recursion Example #1: World’s Simplest Recursion Program Visualizing Recursion –Using Stacks Recursion Example.
Chapter 10 Recursion. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Explain the underlying concepts of recursion.
Chapter 15 Recursive Algorithms. 2 Recursion Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
Recursion A recursive function is a function that calls itself either directly or indirectly through another function. The problems that can be solved.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 15 Recursive Algorithms.
Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer The Power of the Recursive Algorithms.
Recursion Chapter 5.
Data Structures Using C++ 2E Chapter 6 Recursion.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 19: Recursion.
A Review of Recursion Dr. Jicheng Fu Department of Computer Science University of Central Oklahoma.
Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions,
Data Structures Using C++ 2E Chapter 6 Recursion.
Recursion Recursive Algorithms and Backtracking SoftUni Team Technical Trainers Software University
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved11-2 Arrays Arrays are objects that help us organize large amounts of information.
Recursion A method is recursive if it makes a call to itself. A method is recursive if it makes a call to itself. For example: For example: public void.
15-1 Chapter-18: Recursive Methods –Introduction to Recursion –Solving Problems with Recursion –Examples of Recursive Methods.
Recursion.  A recursive function contains a call to itself Example: the factorial n!=n*(n-1)! for n>1 n!=1 for n=1 int factorial (int n) { if (n == 0)
Recursion. Definition Recursion is a function calling on itself over and over until reaching an end state. One such example is factorial. 10! = 10 * 9.
Programming Principles II Lecture Notes 5 Recursion Andreas Savva.
CHAPTER 02 Recursion Compiled by: Dr. Mohammad Omar Alhawarat.
Week 5 - Monday.  What did we talk about last time?  Linked list implementations  Stacks  Queues.
Recursion Textbook chapter Recursive Function Call a recursive call is a function call in which the called function is the same as the one making.
224 3/30/98 CSE 143 Recursion [Sections 6.1, ]
1 7.Algorithm Efficiency What to measure? Space utilization: amount of memory required  Time efficiency: amount of time required to process the data Depends.
1 CSC 427: Data Structures and Algorithm Analysis Fall 2008 Dynamic programming  top-down vs. bottom-up  divide & conquer vs. dynamic programming  examples:
Chapter 4 Recursion. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Explain the underlying concepts of recursion.
Loops Repeating Code Multiple Times SoftUni Team Technical Trainers Software University
1 TCSS 143, Autumn 2004 Lecture Notes Recursion Koffman/Wolfgang Ch. 7, pp ,
Recursion Recursion Chapter 12. Outline n What is recursion n Recursive algorithms with simple variables n Recursion and the run-time stack n Recursion.
Recursion When to use it and when not to use it. Basics of Recursion Recursion uses a method Recursion uses a method Within that method a call is made.
Recursion. What is recursion? Rules of recursion Mathematical induction The Fibonacci sequence Summary Outline.
CSC 221: Recursion. Recursion: Definition Function that solves a problem by relying on itself to compute the correct solution for a smaller version of.
Recursion. Math Review Given the following sequence: a 1 = 1 a n = 2*a n-1 OR a n+1 = 2*a n What are the values of the following? a 2 = a 3 = a 4 =
Java Programming: Guided Learning with Early Objects Chapter 11 Recursion.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 15 * Recursive Algorithms.
1 Recursion Recursion is a powerful programming technique that provides elegant solutions to certain problems. Chapter 11 focuses on explaining the underlying.
Recursion A recursive definition is one which uses the word or concept being defined in the definition itself Example: “A computer is a machine.
Programming With Java ICS201 University Of Ha’il1 Chapter 11 Recursion.
Recursion and Combinatorial Algorithms academy.zariba.com 1.
Recursion Chapter 17 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
Recursion by Ender Ozcan. Recursion in computing Recursion in computer programming defines a function in terms of itself. Recursion in computer programming.
Program Development and Design Using C++, Third Edition
CSC 143 P 1 CSC 143 Recursion [Chapter 5]. CSC 143 P 2 Recursion  A recursive definition is one which is defined in terms of itself  Example:  Compound.
1 7.Algorithm Efficiency These factors vary from one machine/compiler (platform) to another  Count the number of times instructions are executed So, measure.
1 Data Structures CSCI 132, Spring 2016 Notes 16 Tail Recursion.
CS212: Data Structures and Algorithms
Recursive Algorithms and Backtracking
Topic 6 Recursion.
Chapter 15 Recursion.
Chapter 15 Recursion.
Java Software Structures: John Lewis & Joseph Chase
Recursion Copyright (c) Pearson All rights reserved.
Chapter 12 Recursion (methods calling themselves)
The Power of Calling a Method from Itself
Chapter 8 Recursion.
Unit 3 Test: Friday.
Java Programming: Chapter 9: Recursion Second Edition
Recursion James Brucker.
Recursive Algorithms 1 Building a Ruler: drawRuler()
Presentation transcript:

The Power of Calling a Method from Itself Svetlin Nakov Telerik Corporation

1. What is Recursion? 2. Calculating Factorial Recursively 3. Generating All 0/1 Vectors Recursively 4. Finding All Paths in a Labyrinth Recursively 5. Recursion or Iteration? 2

 Recursion is when a methods calls itself  Very powerful technique for implementing combinatorial and other algorithms  Recursion should have  Direct or indirect recursive call  The method calls itself directly or through other methods  Exit criteria (bottom)  Prevents infinite recursion 3

 Recursive definition of n! (n factorial): n! = n * (n–1)! for n >= 0 0! = 1  5! = 5 * 4! = 5 * 4 * 3 * 2 * 1 * 1 = 120  4! = 4 * 3! = 4 * 3 * 2 * 1 * 1 = 24  3! = 3 * 2! = 3 * 2 * 1 * 1 = 6  2! = 2 * 1! = 2 * 1 * 1 = 2  1! = 1 * 0! = 1 * 1 = 1  0! = 1 4

 Calculating factorial:  0 ! = 1  n! = n* (n-1)!, n>0  Don't try this at home!  Use iteration instead static decimal Factorial(decimal num) { if (num == 0) return 1; else return 1; else return num * Factorial(num - 1); } return num * Factorial(num - 1); } The bottom of the recursion Recursive call: the method calls itself 5

Live Demo

 How to generate all 8-bit vectors recursively?  How to generate all n-bit vectors? 7

 Algorithm Gen01(n) : put 0 and 1 at the last position n and call Gen01(n-1) for the rest: 8xxxxxx0Gen01(6): Gen01(5)xxxxxx1Gen01(5)xxxxx0yGen01(5): Gen01(4)xxxxx1yGen01(4)... Gen01(-1)  Stop!

static void Gen01(int index, int[] vector) { if (index == -1) if (index == -1) Print(vector); Print(vector); else else for (int i=0; i<=1; i++) for (int i=0; i<=1; i++) { vector[index] = i; vector[index] = i; Gen01(index-1, vector); Gen01(index-1, vector); }} static void Main() { int size = 8; int size = 8; int[] vector = new int[size]; int[] vector = new int[size]; Gen01(size-1, vector); Gen01(size-1, vector);} 9

Live Demo

 We are given a labyrinth  Represented as matrix of cells of size M x N  Empty cells are passable, the others (*) are not  We start from the top left corner and can move in the all 4 directions: left, right, up, down  We need to find all paths to the bottom right corner 11 Start position End position ***** *****

 There are 3 different paths from the top left corner to the bottom right corner: 12012***3** 654 7***** *8910**3*7* ***** ) 2)012***3** *****9 10 3)

 Suppose we have an algorithm FindExit(x,y) that finds and prints all paths to the exit (bottom right corner) starting from position (x,y)  If (x,y) is not passable, no paths are found  If (x,y) is already visited, no paths are found  Otherwise:  Mark position (x,y) as visited (to avoid cycles)  Find all paths to the exit from all neighbor cells: (x-1,y), (x+1,y), (x,y+1), (x,y-1)  Mark position (x,y) as free (can be visited again) 13

 Representing the labyrinth as matrix of characters (in this example 5 rows and 7 columns):  Spaces (' ') are passable cells  Asterisks (' * ') are not passable cells  The symbol ' e ' is the exit (can be multiple) 14 static char[,] lab = { {' ', ' ', ' ', '*', ' ', ' ', ' '}, {' ', ' ', ' ', '*', ' ', ' ', ' '}, {'*', '*', ' ', '*', ' ', '*', ' '}, {'*', '*', ' ', '*', ' ', '*', ' '}, {' ', ' ', ' ', ' ', ' ', ' ', ' '}, {' ', ' ', ' ', ' ', ' ', ' ', ' '}, {' ', '*', '*', '*', '*', '*', ' '}, {' ', '*', '*', '*', '*', '*', ' '}, {' ', ' ', ' ', ' ', ' ', ' ', 'е'}, {' ', ' ', ' ', ' ', ' ', ' ', 'е'},};

15 static void FindExit(int row, int col) { if ((col = lab.GetLength(1)) if ((col = lab.GetLength(1)) || (row >= lab.GetLength(0))) || (row >= lab.GetLength(0))) { // We are out of the labyrinth -> can't find a path // We are out of the labyrinth -> can't find a path return; return; } // Check if we have found the exit // Check if we have found the exit if (lab[row, col] == 'е') if (lab[row, col] == 'е') { Console.WriteLine("Found the exit!"); Console.WriteLine("Found the exit!"); } if (lab[row, col] != ' ') if (lab[row, col] != ' ') { // The current cell is not free -> can't find a path // The current cell is not free -> can't find a path return; return; } (example continues)

16 // Temporary mark the current cell as visited // Temporary mark the current cell as visited lab[row, col] = 's'; lab[row, col] = 's'; // Invoke recursion the explore all possible directions // Invoke recursion the explore all possible directions FindExit(row, col-1); // left FindExit(row, col-1); // left FindExit(row-1, col); // up FindExit(row-1, col); // up FindExit(row, col+1); // right FindExit(row, col+1); // right FindExit(row+1, col); // down FindExit(row+1, col); // down // Mark back the current cell as free // Mark back the current cell as free lab[row, col] = ' '; lab[row, col] = ' ';} static void Main() { FindExit(0, 0); FindExit(0, 0);}

Live Demo

 How to print all paths found by our recursive algorithm?  Each move's direction can be stored in array  Need to pass the movement direction at each recursive call  At the start of each recursive call the current direction is appended to the array  At the end of each recursive call the last direction is removed form the array 18 static char[] path = new char[lab.GetLength(0) * lab.GetLength(1)]; new char[lab.GetLength(0) * lab.GetLength(1)]; static int position = 0;

19 static void FindPathToExit(int row, int col, char direction) { // Append the current direction to the path // Append the current direction to the path path[position++] = direction; path[position++] = direction; if (lab[row, col] == 'е') if (lab[row, col] == 'е') { // The exit is found -> print the current path // The exit is found -> print the current path } // Recursively explore all possible directions // Recursively explore all possible directions FindPathToExit(row, col - 1, 'L'); // left FindPathToExit(row, col - 1, 'L'); // left FindPathToExit(row - 1, col, 'U'); // up FindPathToExit(row - 1, col, 'U'); // up FindPathToExit(row, col + 1, 'R'); // right FindPathToExit(row, col + 1, 'R'); // right FindPathToExit(row + 1, col, 'D'); // down FindPathToExit(row + 1, col, 'D'); // down // Remove the last direction from the path // Remove the last direction from the path position--; position--;}

Live Demo

When to Use and When to Avoid Recursion?

 When used incorrectly the recursion could take too much memory and computing power  Example: static decimal Fibonacci(int n) { if ((n == 1) || (n == 2)) if ((n == 1) || (n == 2)) return 1; return 1; else else return Fibonacci(n - 1) + Fibonacci(n - 2); return Fibonacci(n - 1) + Fibonacci(n - 2);} static void Main() { Console.WriteLine(Fibonacci(10)); // 89 Console.WriteLine(Fibonacci(10)); // 89 Console.WriteLine(Fibonacci(50)); // This will hang! Console.WriteLine(Fibonacci(50)); // This will hang!} 22

Live Demo

24  fib(n) makes about fib(n) recursive calls  The same value is calculated many, many times!

 Each Fibonacci sequence member can be remembered once it is calculated  Can be returned directly when needed again 25 static decimal[] fib = new decimal[MAX_FIB]; static decimal Fibonacci(int n) { if (fib[n] == 0) if (fib[n] == 0) { // The value of fib[n] is still not calculated // The value of fib[n] is still not calculated if ((n == 1) || (n == 2)) if ((n == 1) || (n == 2)) fib[n] = 1; fib[n] = 1; else else fib[n] = Fibonacci(n - 1) + Fibonacci(n - 2); fib[n] = Fibonacci(n - 1) + Fibonacci(n - 2); } return fib[n]; return fib[n];}

Live Demo

 Avoid recursion when an obvious iterative algorithm exists  Examples: factorial, Fibonacci numbers  Use recursion for combinatorial algorithm where at each step you need to recursively explore more than one possible continuation  Examples: permutations, all paths in labyrinth  If you have only one recursive call in the body of a recursive method, it can directly become iterative (like calculating factorial) 27

 Recursion means to call a method from itself  It should always have a bottom at which recursive calls stop  Very powerful technique for implementing combinatorial algorithms  Examples: generating combinatorial configurations like permutations, combinations, variations, etc.  Recursion can be harmful when not used correctly 28

Questions?

1. Write a recursive program that simulates execution of n nested loops from 1 to n. Examples: n=2 -> 1 2 n=3 ->

2. Write a recursive program for generating and printing all the combinations with duplicates of k elements from n-element set. Example: n=3, k=2  (1 1), (1 2), (1 3), (2 2), (2 3), (3 3) 3. Write a recursive program for generating and printing all permutations of the numbers 1, 2,..., n for given integer number n. Example: n=3  {1, 2, 3}, {1, 3, 2}, {2, 1, 3}, {2, 3, 1}, {3, 1, 2},{3, 2, 1} 31

4. Write a recursive program for generating and printing all ordered k-element subsets from n- element set (variations V k n ). Example: n=3, k=2 (1 1), (1 2), (1 3), (2 1), (2 2), (2 3), (3 1), (3 2), (3 3) 5. Write a program for generating and printing all subsets of k strings from given set of strings. Example: s = {test, rock, fun}, k=2 (test rock), (test fun), (rock fun) 32

6. We are given a matrix of passable and non-passable cells. Write a recursive program for finding all paths between two cells in the matrix. 7. Modify the above program to check whether a path exists between two cells without finding all possible paths. Test it over an empty 100 x 100 matrix. 8. Write a program to find the largest connected area of adjacent empty cells in a matrix. 9. Implement the BFS algorithm to find the shortest path between two cells in a matrix (read about Breath-First Search in Wikipedia). Breath-First Search Breath-First Search 33

6. We are given a matrix of passable and non-passable cells. Write a recursive program for finding all areas of passable cells in the matrix. 10. Write a recursive program that traverses the entire hard disk drive C:\ and displays all folders recursively and all files inside each of them. 34