<h2>
Tower of Hanoi Algorithm
</h2>
<h4>
Enter Number of Disks: <input type="textbox" id="tbSize" value="7" />
</h4>
<div>
<input type="button" id="btnSolve" value="Solve!" onclick="solve()" />
<br/>
</div>
<h4>
Number of moves to solve Tower of Hanoi:
</h4>
<div id="output" />
JavaScript
//create stack
Stack = function(){
this.head = null;
this.size = 0;
}
Node = function(_item){
this.item = _item;
this.next = null;
}
//push method
Stack.prototype.push = function(_item){
var node = new Node();
node.item = _item;
if (this.head){
node.next = this.head;
this.head = node;
}
else{
this.head = node;
}
this.size++;
}
//pop method
Stack.prototype.pop = function(){
if(this.head){
var popped = this.head;
this.head = this.head.next;
this.size--;
return popped.item;
}
else{
console.log("There is nothing on the stack");
return false;
}
}
//toString method
Stack.prototype.toString = function(){
var s = "";
var node = this.head;
while(node != null){
s += node.item + " ";
node = node.next;
}
return s;
}
//global move counter variable
var n = 0;
//solve tower of hanoi function
var solve = function(){
//instantiate stack objects
var stackA = new Stack();
var stackB = new Stack();
var stackC = new Stack();
//reset global counter to zero
n=0;
//parse user input
var i = parseInt(document.getElementById("tbSize").value);
for(var t = i; t > 0; t--){
stackA.push(t);
}
//output and run algorithm
document.getElementById("output").innerHTML = "<br/>Stack A Before: " + stackA.toString();
document.getElementById("output").innerHTML += "<br/>Stack B Before: " + stackB.toString();
runHanoi(i, stackA, stackB, stackC);
document.getElementById("output").innerHTML += "<br/>Stack A After: " + stackA.toString();
document.getElementById("output").innerHTML += "<br/>Stack B After: " + stackB.toString();
document.getElementById("output").innerHTML += "<br/>Congratulations! You solved the Towers of Hanoi in " + n + " moves.";
}
//tower of hanoi algorithm
function runHanoi(z, A, B, C){
if (z == 1){
move(A, B);
n++;
}
else{
//recursive call
runHanoi(z-1, A, C, B);
move(A, B);
n++;
runHanoi(z-1, C, B, A);
...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.