Skip to content

Instantly share code, notes, and snippets.

@cacciatc
Created January 16, 2013 22:58
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 cacciatc/4551762 to your computer and use it in GitHub Desktop.
Save cacciatc/4551762 to your computer and use it in GitHub Desktop.
Render move solutions to n-disked Tower Of Hanoi puzzles.
load(__folder + "drone.js");
Drone.extend("toh",function(dc){
var d = this;
var tf = function(dc){
var ta = [];
var tb = [];
var tc = [];
for(var i = dc;i > 0; i--){
ta.push(i);
}
var history = [{a:ta.slice(0),b:tb.slice(0),c:tc.slice(0)}];
var hanoi = function(n, source, by, dest){
if(n == 0) return;
hanoi(n-1,source,dest,by);
if(source == 'A'){
ta.pop();
}
else if(source == 'B'){
tb.pop();
}
else if(source == 'C'){
tc.pop();
}
if(dest == 'A'){
ta.push(n);
}
else if(dest == 'B'){
tb.push(n);
}
else if(dest == 'C'){
tc.push(n);
}
history.push({a:ta.slice(0),b:tb.slice(0),c:tc.slice(0)});
hanoi(n-1,by,source,dest);
}
var draw = function(frame){
d.chkpt("s");
draw_col(frame.a);
d.right(1);
draw_col(frame.b);
d.right(1);
draw_col(frame.c);
d.right(1);
d.move("s");
}
var draw_col = function(a){
d.chkpt("d");
for(var i = 0;i < a.length; i++){
if(a[i] == 1){
d.box('35:1').up();
}
else if(a[i] == 2){
d.box('35:2').up();
}
else if(a[i] == 3){
d.box('35:3').up();
}
else if(a[i] == 4){
d.box('35:4').up();
}
else if(a[i] == 5){
d.box('35:5').up();
}
else if(a[i] == 6){
d.box('35:6').up();
}
else if(a[i] == 7){
d.box('35:7').up();
}
else if(a[i] == 8){
d.box('35:8').up();
}
else if(a[i] == 9){
d.box('35:9').up();
}
else if(a[i] == 10){
d.box('35:10').up();
}
}
d.move("d");
}
hanoi(dc,'A','B','C');
while(history.length > 0){
var frame = history.shift();
draw(frame);
d.fwd(1);
}
}
tf(dc);
return this;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment