Skip to content

Instantly share code, notes, and snippets.

@vidul-nikolaev-petrov
Last active August 29, 2015 14:17
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 vidul-nikolaev-petrov/1c18c70523c19799b10f to your computer and use it in GitHub Desktop.
Save vidul-nikolaev-petrov/1c18c70523c19799b10f to your computer and use it in GitHub Desktop.
Tower of Hanoi
/**
* Thst is not the optimal formula, don't use it.
* This is just another solution for the algorithm
* Tower of Hanoi.
*/
if (Array.prototype.last === undefined) {
Array.prototype.last = function () {
return this.length ? this[this.length - 1] : 0;
};
};
var a = [3, 2, 1],
b = [],
c = [],
counter = 0;
function swap(a1, a2) {
a1.push(a2.pop());
}
function compareAndReplace(a1, a2) {
if (!a1.length && !a2.length) {
return;
}
if (!a2.last()) {
swap(a2, a1);
return true;
}
if (!a1.last()) {
swap(a1, a2);
return true;
}
if (a1.last() > a2.last()) {
swap(a1, a2);
}
else {
swap(a2, a1);
}
return true;
}
function towerOfHanoi(a, b, c) {
if (!a.length && !b.length) {
return [a, b, c];
}
compareAndReplace(a, b) && logger(a, b, c);
compareAndReplace(a, c) && logger(a, b, c);
compareAndReplace(b, c) && logger(a, b, c);
return towerOfHanoi(a, b, c);
}
function logger(lists) {
++counter && console.log(counter, '>', 'A:', a, 'B:', b, 'C:', c);
}
towerOfHanoi(a, b, c);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment