<H4>
The Big O notation is 2^n - 1 <br/> I believe that the world may come to an end when the puzzle is completed. Only because the puzzle wouldn't be complete before the world was destroyed.
</H4>
<input type="textbox" id="value" value= "3" />
<br/>
<input type="button" value="ENTER" onClick="AddToStack();" />
<p id='output1'></p>
JavaScript
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) {
return null;
}
if (this.bottom == this.top) {
var a = this.top.content;
this.bottom = null;
this.top = null;
return a;
}
var a = this.top.content;
this.top = this.top.last;
this.top.next = null;
return a;
}
}
var A = new Stack();
var B = new Stack();
var C = new Stack();
var counter = 0;
function AddToStack() {
var n = document.getElementById("value").value;
for(i=n; i>=1; i--){
A.push(i);
}
TowerofHanoi(n,A,B,C);
document.getElementById('output1').innerHTML = "Minimum amount of moves to solve: " + counter;
}
function TowerofHanoi(n,source,spare,dest){
if(n>0){
TowerofHanoi(n-1,source,dest,spare);
var disk = source.pop();
dest.push(disk);
counter++;
TowerofHanoi(n-1,spare,source,dest);
}
}
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.