towers of hanoi recursive towers of hanoi

Practical Recursion

The Towers of Hanoi

by Robert Deveau 2013


Return to Practical Recursion Home








Moves will appear here *8 disks max

Recursive algorithm

Recall that we 'Always, Always, Always' start with an algorithm. Whether you devise the algorithm yourself or are supplied one, turning the algorithm into usable code may not be easy.

Recall that we 'Always, Always, Always' start with an algorithm. Whether you devise the algorithm yourself or are supplied one, turning the algorithm into usable code may not be easy. Also recall that our objective is to practice thinking recursively.



To move n discs from src to dst: function hanoi(disc, src, aux, dst) //the initial call
First move N-1 disks from src to aux. hanoi(disc - 1, src, dst, aux); //each function call means to first do this
Move disk n from src to dst. hanoisol +=('Move disc '+disc+' from '+src+' to '+dst);//print the move
Move N-1 discs from aux to dst. hanoi(disc - 1, aux, src, dst);//but first do this

Carnegie Mellon University has a nice TOH implementation which can help you visualize the problem and solution. However, they use the center peg as their destination.

Remember that each function call pushes that operation onto the stack, and each move, will pop the stack.

Using your coin model, make an additional set of labels or a diagram to see how each of the arguments will change as they go into the parameters of the function hanoi(disc, src, aux, dst). Then you can see how the code matches the algorithm.

Analogy

"Teaching recursion with the factorial example and assigning the Towers of Hanoi as an exercise is like showing someone how to build a birdhouse and assigning them to build the White House."- R. Deveau.

Don't worry, it gets much worse. Next up is Fractals or Return to home page.

©2013 deveau enterprises