Thinking about recursion problems
- Understand the pattern.
Draw out the first couple of cases involving the smallest number of recursive calls. You should understand how to create the pattern given any arguments for the pattern. - What is the base case?
Endless loops are bad. When does the recursive method stop? - Identify a single recursion layer.
What distinguishesrecursion_method(level)
fromrecursion_method(level-1)
? What is added on with each additional level of recursion? - Figure out how to move to the next recursion layer.
Once we have executed a single recursion layer, we need to move into position to execute the next recursion layer. What is this pattern? It should be the same no matter which two recursion layers we are moving between. - What is the next recursion layer call?
Generally, the arguments will have to be modified for the next level (or else we'd create an endless loop) - How do we meet our invariant, if any?
In order for recursive methods to work, they must meet strictly defined behaviours. Often, this means that objects must be placed in their starting positions before exiting the method (for drawing recursive picture patterns).
Programming recursion solutions
- Follow all the steps in Thinking about recursion problems (above), first.
- Write all code on paper first. Try it out line by line using our brain and pencil and paper with the simplest test cases to make sure it works.
- Finally, type the code into the computer and test it out. Do this incrementatlly, as you would for any program. Try to type and test one method at a time using stubs for other methods. Be sure that each test version will terminate!
- SAVE files before every compilation. It is very easy to accidentally create an endless loop when solving recursion problems. If we try to run our program and it has an endless loop, we will hang the computer and perhaps be forced to restart.
- Use System.out.println() in all our methods to help with debugging.