Towers of Hanoi

| 1 Comment

This one was dug up from my archives....

How to Solve the Towers of Hanoi with Flash MX

The main thing to get from this example is how simple the algorithm is, and to show how powerful recursion can be. For those not familiar with recursion - recursion is the process of a function calling itself.

There are always 2 "cases" in a recursive function - the "base case" that signals the end of the recursion, and the "recursive case." Recursion is a way of problem simplification. If you don't know how to solve a problem, a common approach is to break the problem down into smaller pieces, and this is exactly what recursion does. The "recursive case" reduces the problem into a more solveable problem, until eventually the "base case" is found, which we can easily solve. Then, the result "bubbles up" to the top level for the complete answer.

A very typical example of this is with the factorial function. We know that 1! and 0! are both 1, and that 2! is 2 * 1!... so, in general, n! = n * (n-1)!. This definition fits the recursive definition perfectly.

function factorial(n) { if (n <= 1) { // the base case - a problem easily solved return 1; } else { /* the recursive case, a slightly harder problem to solve, but can be broken down into a smaller problem */ return n * factorial(n-1); /* in the statement above, the factorial(n-1) function is evaluated first, then n gets multiplied by that value, and then the return takes place. */ } }

I won't get too detailed about how this effect is achieved in memory, but there are two important things to note.

1) Any recursive algorithm can be written as a while loop. This is vital to proving algorithm correctness from a computer science perspective. However, recursive solutions tend to be more understandable over iterative solutions (e.g. while loops), once you can overcome the hurdle of "how the heck can a function call itself???."

2) Recursive solutions are generally more memory-intesive, as each function call gets pushed on the stack along with a copy of the local variables as well. While loops will perform faster, but are generally not as intuitive.

1 Comment

hey Dorron!

I appreciate ur work and its well done!...but do u have the actionsscripts for the Towers of Hanoi for flash 2004 MX, I need to understand it with briks and so on....if u can help then mail me back at mcgerell@hotmail.com

Leave a comment



About this Entry

This page contains a single entry by darron published on July 28, 2003 7:35 PM.

Life in the Way was the previous entry in this blog.

traceObject is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.

Archives

OpenID accepted here Learn more about OpenID
Powered by Movable Type 5.02