Send Close Add comments: (status displays here)
Got it!  This site uses cookies. You consent to this by clicking on "Got it!" or by continuing to use this website.nbsp; Note: This appears on each machine/browser from which this site is accessed.
Towers of Hanoi: Recursion to iteration 1


1. Towers of Hanoi: Recursion to iteration 1
These notes are a start at converting nontrivial recursion to iteration.

Study these notes so that when we complete the process you will be familiar with the starting point used here.

2. Recursion to iteration
A recursively defined and implemented solution is elegant and easy to reason about for correctness purposes.

However, converting recursion to iteration show how the underlying runtime stack mechanism for access to local variables works. Below is a progressive example that shows one way how nontrivial recursion (i.e., more than one recursive call in a recursive function) can be converted to iteration.

As a starting point, below is a solution to the Towers of Hanoi problem for 3 disks (to reduce the amount of output for example purposes).

3. Starting program
Here is the JavaScript code.

Here is the output of the JavaScript code.


4. Expand code
The first step is as follows. Here is how this might be done. Note the following. Machine efficiency is not a concern at this point. Here is the JavaScript code.

Here is the output of the JavaScript code.


5. Add states
The next step is as follows. Here is how this might be done. Note the following. Here is the JavaScript code.

Here is the output of the JavaScript code.


6. Runtime memory
Runtime memory is often divided into the following.

7. Add a variable runtime stack
The next step is as follows. Here is how this might be done. Here is the JavaScript code.

Here is the output of the JavaScript code.


8. End of page