The key to writing recursive code is understanding that recursion is "defining something in terms of itself." So the best way to approach recursive code is by finding the base case of what you're trying to do and writing code for that. From then on, the trick is to just have the function call itself repeatedly until it reaches the base case; therefore the only thing the code actually does is whatever is in the base case.
Throughout the weeks of learning recursion it seemed simple enough. Tracing through codes was tedious but eventually a pattern could be found that convinced me that the code was just repeating the base case multiple times. But actually writing recursive code was a whole different ball game!
While doing A1, and reading through the notes on recursion, I learned that there are two ways of viewing recursion. The low-level operational view, and the high-level view. For example, step 5 of the assignment, writing a recursive method of solving the tours of anne hoy game for n number of cheeses on 4 stools, can be represented by both views.
The low level view can be represented by breaking it into steps thereby eliminating recursion. This would involve writing code for moving 1 cheese, and then calling that to move 2 cheeses in a new function, then calling 2 cheeses to move 3 cheeses etc. This method would be impossible to write for an infinite amount of cheeses though. So the objective was to use the high-level view which involved "Taking a leap of faith." This is where you write code for 1 cheese and convince yourself it works for 1 cheese, within the main function "tour_of_four_stools." And then you can call this function within itself for any number of cheeses larger than 1. For n number of cheeses, by calling this function within itself on n-1, whenever n > 1, eventually n =1, and at that point the code you wrote for n=1 is executed. This happens repeatedly until n amount of cheeses are moved, and the puzzle is solved!
Although recursion seems complicated it is actually a very effective and useful way of simplifying a situation into smaller parts and makes solving coding problems much easier.
No comments:
Post a Comment