Towers of Hanoi
by vzufelt
HTML
<h4>
Please enter the number of disks: <input id='uInput' type='textbox' value="5">
</h4>
<br>
<button id=calc onClick='run()'>Calculate number of moves</button>
<div id='output1'>
</div>
JavaScript
var num = 0;
var Node = function(_content) {
this.next = null;
this.last = null;
this.content = _content;
}
var Stack = function() {
this.bottom = null;
this.top = null;
this.push = function(_content) {
if (this.bottom == null) {
this.bottom = new Node(_content);
this.top = this.bottom;
return this;
}
var addedNode = new Node(_content);
addedNode.last = this.top;
this.top.next = addedNode;
this.top = addedNode;
return this;
}
this.pop = function() {
if (this.bottom == null) {
alert("The Stack is Empty");
return null;
}
if (this.bottom == this.top) {
var n = this.top;
this.top = null;
this.bottom = null;
return n;
}
var a = this.top;
this.top = this.top.last;
this.top.next = null;
return a;
}
this.toString = function() {
var str = "";
var node = this.bottom;
while (node != null) {
str += node.content + ":";
node = node.next;
}
return str;
}
}
function run() {
var stackA = new Stack();
var stackB = new Stack();
var stackC = new Stack();
var i = parseInt(document.getElementById('uInput').value);
for (var t = i; t > 0; t--) {
stackA.push(t);
}
document.getElementById('output1').innerHTML = '<br/>Stack A Before: ' + stackA.toString();
document.getElementById('output1').innerHTML += '<br/>Stack B Before: ' + stackB.toString();
runHanoi(i, stackA, stackB, stackC);
document.getElementById('output1').innerHTML += '<br/>Stack A After: ' + stackA.toString();
document.getElementById('output1').innerHTML += '<br/>Stack B After: ' + stackB.toString();
document.getElementById('output1').innerHTML += '<br/><br/>Congratulations! You solved the Towers of Hanoi in ' + num + ' moves.';
}
function runHanoi(z, A, B, C) {
if (z == 1) {
move(A, B);
num++;
} else {
runHanoi(z - 1, A, C, B);
move(A, B);
num++;
runHanoi(z - 1, C, B, A);
}
}
function move(A, B) {
...