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 2


1. Towers of Hanoi: Recursion to iteration 2
This page continues the page at Towers of Hanoi: Recursion to iteration 1 .

2. More states
Let us now move the states from 4 to 6 to include the processing right after entry and the processing right before exit.

The local state1 variable is also added as a parameter to the move routine and adjusted in each place.

Here is the JavaScript code.

Here is the output of the JavaScript code.


3. More states
Finally, let us make multiple switches in the following manner. Here is the JavaScript code.

Here is the output of the JavaScript code.


4. Simplification
At this point, some simplifications become apparent that will now be made. These simplifications could have been made earlier, with proper insight, but will be made now.

Note that if n1 is zero then the next state is always 4 without any intervening change. This allows the case where n1 is zero to move directly from state 0 to state 4.

Below is the code with this change.

Here is the JavaScript code.

Here is the output of the JavaScript code.


5. Starting code comparison
Let us compare the above iteration code with the starting recursive code. Which code is more clear?

Here is the JavaScript code.

Here is the output of the JavaScript code.


6. Observations
The following observations can be made. The correctness of the iterative version follows from making invariant transformations from the original code. This is a common technique for showing that "improved" code (e.g., more machine efficient, etc.) is correct.

7. End of page