
Solve the formula of hanoi towers code#
If we are to implement the delay by a spin-loop, it would bring things to a stand-still because the whole of JavaScript code executes on one thread. However, JavaScript lacks a "real" delay or sleep mechanism. One might suggest that the caller sleeps for a while to allow for animation to complete. A problem arises because code in the caller will continue executing and interfere (miss up shared data) with the animation. Suppose, in the above code, the call to the function moveDisk() is animated using setInterval(). Normally animation code can utilize JavaScript timer functions: setInterval() or setTimer(). Animation Handling in JavaScript is Problematic The above algorithm encodes the preceding description but with the parameters for the towers kept as variables instead of being specific values. After this, we can move the n-th disk from tower #0 to tower #2 and then move all the n-1 disks from the middle tower to the last tower using tower #0 as intermediate by the call Hanoi(n-1, 1,2,0). This moves the disks to the middle tower (#1) using the other tower (#2) as intermediate.


The recursive algorithm for the tower of Hanoi is based on observing that the top n-1 disks at the "from" tower (together with the other two towers) represent a smaller-size instance of the original problem and, thus, can be solved by the call Hanoi(n-1, 0,1,2). Then express the solution for the original problem in terms of the solutions to the subproblems. Normally (if we denote the towers with 0,1,2), the initial call for n disks will be Hanoi(n,0,2,1).Ī recursive algorithm normally tries to find subproblems (instances of the original problem but with smaller problem size).

from: the "from" tower is where the disks are placed.n: number of disks serves as the problem size for recursion.The input to the algorithm are 4 integer parameters, as follows: callStack.push() // save parameters to callStack array Copy Code function Hanoi(n, from, to, via)
