Created
February 28, 2013 13:39
-
-
Save abozhilov/5056778 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var hanoi = function (n) { | |
/** | |
* Index of the cols is the current position of the disc. | |
* The value is the transition column. | |
* When the N minus disc number is even number, use the first row of the table. | |
* Otherwise when the number is odd use the second. | |
*/ | |
var STATE_TABLE = [ | |
[2, 0, 1], | |
[1, 2, 0] | |
]; | |
var arr = [], len = n - 1, | |
curr_row, moves = []; | |
for (var i = n; i--;) arr[i] = 0; | |
/** | |
* To solve the hanoi towers we need N inner loops. | |
* Every loop should start with lower value of the current index in surounded loop. | |
* We use recursion as we don't know the particular value of N. | |
* Also the recursion keeps the code simple. | |
* The algorithm complexity is O(2^N). To prove that we can use a math induction. | |
*/ | |
(function solve(n) { | |
while (n--) { | |
solve(n); | |
curr_row = arr[n]; | |
arr[n] = STATE_TABLE[(len - n) % 2][curr_row]; | |
moves.push([n, curr_row, arr[n]]); | |
} | |
})(n); | |
return moves; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment