Skip to content

Instantly share code, notes, and snippets.

@fehmicansaglam
Created February 13, 2012 10:59
Show Gist options
  • Save fehmicansaglam/1816052 to your computer and use it in GitHub Desktop.
Save fehmicansaglam/1816052 to your computer and use it in GitHub Desktop.
jQuery HanoiTowers Solver
<html>
<head>
<title>Hanoi</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<style type="text/css">
#hanoi-table {
width: 345px;
height: 18px;
background-color: #eee;
border: 4px solid #ccc;
position: absolute;
bottom: 100px;
left: 0;
}
.hanoi-peg {
width: 7px;
height: 150px;
position: absolute;
bottom: 125px;
background-color: LawnGreen;
border: 4px solid ForestGreen;
}
#hanoi-peg-1 {
left: 50px;
}
#hanoi-peg-2 {
left: 165px;
}
#hanoi-peg-3 {
left: 280px;
}
.hanoi-disc {
height: 15px;
background-color: blue;
position: absolute;
border: 1px solid royalblue;
-webkit-border-radius: 4px 4px 4px 4px;
-moz-border-radius: 4px 4px 4px 4px;
border-radius: 4px 4px 4px 4px;
}
</style>
</head>
<body>
<div id="hanoi-table"></div>
<div id="hanoi-peg-1" class="hanoi-peg"></div>
<div id="hanoi-peg-2" class="hanoi-peg"></div>
<div id="hanoi-peg-3" class="hanoi-peg"></div>
</body>
<script type="text/javascript">
(function(){
function Peg(bottom, left){
this.bottom = bottom;
this.left = left;
this.discs = new Array();
}
Peg.prototype.push = function(disc){
this.discs.push(disc);
};
Peg.prototype.pop = function(){
return this.discs.pop();
}
Peg.prototype.discCount = function(){
return this.discs.length;
}
var move = function(motions, index) {
if(index == motions.length)
return;
var motion = motions[index];
var from = motion[0];
var to = motion[1];
var disc = pegs[from].pop();
pegs[to].push(disc);
var bottom = pegs[to].bottom + ((pegs[to].discCount()-1)*15);
var left = pegs[to].left - (disc.width() - 15)/2;
disc
.animate({
bottom: (pegs[to].bottom + 150 + 6)
}, 800, 'linear')
.animate({
left: left
}, 800, 'swing')
.animate({
bottom: bottom
}, 800, function() {
move(motions, ++index);
});
}
//create discs
var pegs = new Array();
pegs[1] = new Peg(125, 50);
pegs[2] = new Peg(125, 165);
pegs[3] = new Peg(125, 280);
var discCount = 10;
for(var i=0; i<discCount; i++){
var disc = $('<div></div>',{
class: 'hanoi-disc',
}).css({
width: (76-i*6)+'px',
left: (20+3*i)+'px',
bottom: (125+i*15)+'px',
'z-index': 1000
}).prependTo('body');
pegs[1].push(disc);
}
var motions = new Array();
var hanoiSolver = function(n, start, aux, end){
if(n == 0)
return;
hanoiSolver(n-1, start, end, aux);
motions.push([start, end]);
hanoiSolver(n-1, aux, start, end)
}
hanoiSolver(discCount, 1, 2, 3);
move(motions, 0);
})();
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment