Last active
August 29, 2015 14:17
-
-
Save vidul-nikolaev-petrov/1c18c70523c19799b10f to your computer and use it in GitHub Desktop.
Tower of Hanoi
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
/** | |
* 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