Skip to content

Instantly share code, notes, and snippets.

@abozhilov
Last active December 14, 2015 03:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abozhilov/5024185 to your computer and use it in GitHub Desktop.
Save abozhilov/5024185 to your computer and use it in GitHub Desktop.
Hanoi tower
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