Recently I encounter a new type of coding method, which is recursion. It is not only a new 'technique' I learn to programming, but also a remarkable insight of specific problems.
What is recursion in programming? From my experience, I think it is a method of recalling function itself. For instance, when you build up a function f(x), inside it you call f(x). In this way, when computer execute to that line, it will automatically plug in new input and execute f(new_x) again.
Although it is resemble to looping to some extend, recursion provides us benefits more than that. Namely, it provides us thoughts to splits complex but recursive problems down. In this way, the programmer only need to code program in one iteration and let computer do the rest. For example, in A1, we need to program a solution to solve the Hanoi tower puzzle (of three stools). Although the number of cheese is unknown, we can still find out the general 'rule', which is just move the top (n - 1) cheese onto the 'helper' and base to the 'destination'. Each time moving n cheese is asked, you can recursively think of moving (n - 1) cheeses until the base case, which is just one left. Without recursion this task seems impossible because you even don't know how many cheeses you have! Generally, recursion is required when a task has uncertain sub_tasks resemble to itself.
However, recursion easily raise some problems. The most significant I met is that the execution is booming at a exponential speed thus easily cause problems. Sometimes you may not be able to think through and leave 'leaks' which allow it recurse out of range. Also compared to same times of loops, it will cost more time to solve it. Believe it or not, when I run 150 cheeses on my computer, it takes around 2 minutes to generate answer. After that, each cheese I add would cost times of that time and finally my computer could do nothing besides burn!
No comments:
Post a Comment