Please enter number of disks:<input type="text" id="value"/>
<input type="button" id="submit" value="Calculate number of moves" onclick="submit()" />
<div id="output">
</div>
JavaScript
function Node(_content){
this.next = null;
this.last = null;
this.content= _content;
}
function Stack(){
this.bottom = null;
this.top = null;
this.push = function(_content){
//No head --create
if(this.bottom == null){
this.bottom = new Node(_content);
this.top = this.bottom;
return this.bottom.content;
}
//if has a head add a node
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){
this.bottom = this.top
return this.top.content;
}
// Now remove top Node
var a = this.top; // hold value for return
this.top = this.top.last;
this.top.next = null;
return a.content;
}
this.toString= function(){
var l= "";
var node= this.bottom;
while(node != null){
l += node.content + " : ";
node = node.next;
}
return l;
}
}
function submit(){
var count=1;
var from = new Stack();
var to = new Stack();
var aux = new Stack();
//Fill original stack
var N = parseInt(document.getElementById("value").value);
for(var i = N; i > 0 ; i--){
from.push(i);
}
document.getElementById("output").innerHTML = "<br/> Stack A before : " + from.toString();
document.getElementById("output").innerHTML += "<br/> Stack B before : " + to.toString();
//from as Source , to as Destination, aux as Auxillary
runHanoi(N, from, to, aux );
document.getElementById("output").innerHTML += "<br/> Stack A after : " + from.toString();
document.getElementById("output").innerHTML += "<br/> Stack B after : " + to.toString();
document.getElementById("output").innerHTML += "<br/> Congratulations !! You solved the Tower of Hanoi in " + count + " moves."
function runHanoi(N, from, to, aux){
if(N == 0){
return ;
}
if(N ==1 ){
moveDisk(from,to);
console.log("Move disc "+ N + " from " + from + " to " + to +" <br/>.");
/*console.log("Move disc "+ N + " from " + from + " to " + to +"...
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.