Last active
December 14, 2015 03:49
-
-
Save abozhilov/5024185 to your computer and use it in GitHub Desktop.
Hanoi tower
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) { | |
var STATE_TABLE = [ | |
[2, 0, 1], | |
[1, 2, 0] | |
]; | |
var arr = [], len = n - 1, | |
curr_row, idx, | |
moves = []; | |
for (var i = n; i--;) arr[i] = 0; | |
(function solve(n) { | |
if (n > 0) { | |
solve(n - 1); | |
idx = n - 1; | |
curr_row = arr[idx]; | |
arr[idx] = STATE_TABLE[(len - idx) % 2][curr_row]; | |
solve(n - 1); | |
} | |
})(n); | |
return arr; | |
}; | |
console.log(hanoi(3)); | |
console.log(hanoi(4)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment