Skip to content

Instantly share code, notes, and snippets.

@ironboy
Created August 30, 2015 22:42
Show Gist options
  • Save ironboy/b866a62c867cfc7283c1 to your computer and use it in GitHub Desktop.
Save ironboy/b866a62c867cfc7283c1 to your computer and use it in GitHub Desktop.
Towers of Hanoi - non-recursive
/*
Towers of Hanoi
(non-recursive solution)
https://blog.svpino.com/2015/06/07/programming-challenge-towers-of-hanoi
*/
function solveHanoi(discs){
var towers = {a:[],b:[],c:[]};
function view (){
var t = JSON.parse(JSON.stringify(towers));
var x = "", y;
for(var i = 0; i <= discs-1;i++){
y = "";
for(var j in towers){
y += (t[j].pop() || " ") + " | ";
}
y += "\n";
x = y + x;
}
return "\n"+x;
}
// Disc size 1-discs, 1 = smallest
var k = discs+1;
while(k-->1){towers.a.unshift(k);}
console.log("START",view());
// First move
var move = 1, movedone, smallest = ["a"];
smallest.unshift(discs%2 ? "c" : "b");
towers[smallest[0]].unshift(towers.a.shift());
console.log("MOVE " + move,view());
// Rest moves
while(towers.c.length < discs){
move++;
movedone = false;
for(var i in towers){
if(movedone){break;}
if(towers[i][0]){
for(var j in towers){
if(i==j || towers[i][0]==1){continue;}
if(!towers[j][0] || towers[j][0]>towers[i][0]){
towers[j].unshift(towers[i].shift());
console.log("MOVE " + move,view());
movedone = true;
}
}
}
}
move++;
smallest = smallest.slice(0,2);
for(var i in towers){
if(smallest.indexOf(i)<0){
towers[i].unshift(towers[smallest[0]].shift());
smallest.unshift(i);
console.log("MOVE " + move,view());
break;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment