A7
by Ebony McCoy
HTML
Enter a number between 1 and 7 to complete the Tower of Hanoi
<br>
<br>
<input type="textbox" id="content">
<button id=calc onClick="pushNode();">Tower of Hanoi</button>
<p id='output1'></p>
<p id='output2'></p>
The Big O Complexity for this algorithm is O((2^n)-1).
<br>
<br>
<br>
We should not be concerned with concerned with the legend of the world ending when the 64 disk solution is physically solved because if the legend were true, and if the priests were able to move disks at a rate of one per second, using the smallest number of moves it would take them 264 − 1 seconds or roughly 585 billion years to finish.
CSS
function Hanoi(source, des, aux) {
if (disc==1) {
des.push(source.pop(1));
moves++;
return;
}
else {
Hanoi(disc - 1, source, des, aux);
des.push(source.pop(1));
moves++;
Hanoi(disc - 1, source, des, aux);
des.push(source.pop(1));
return
}
document.getElementbyId("output2").innerHTML="Final Stack (P1: "+source+"P2: "+des+"P3: )"+aux;
}
JavaScript
var d;
var moves = 0;
var Node = function(_content) {
this.next = null;
this.last = null;
this.content = _content;
}
// create stack
var Stack = function(_content) {
this.tail = null;
this.head = null;
this.length = 0;
}
Stack.prototype.push = function(_content) {
var node = new Node(_content);
if (this.length) {
this.tail.next = node;
node.last = this.tail;
this.tail = node;
} else {
this.head = node;
this.tail = node;
}
this.length++;
return node;
// var addNode = new Node(_value);
// addedNode.last = this.top;
// this.top.next = addedNode;
// this.top = addedNode;
// return this;
}
Stack.prototype.pop = function(_content) {
var node = this.tail;
if (node.last) {
node.last.next = node.next;
} else {
this.head = node.next;
}
if (node.next) {
node.next.last = node.last;
} else {
this.tail = node.last;
}
this.length--;
return node;
}
Stack.prototype.toString = function() {
var str = "";
var node = this.head;
while (node !== null) {
str += node.content + " ";
node = node.next;
}
return str;
}
function pushNode() {
var p1 = new Stack();
var p2 = new Stack();
var p3 = new Stack();
var numNodes = document.getElementById("content").value;
//p1.push(i);
for (var i = numNodes; i >= 1; i--) {
p1.push(i);
}
Hanoi(numNodes, p1, p2, p3);
document.getElementById('output1').innerHTML = "Original Stack (P1: " + p1 + "P2: " + p2 + "P3: " + p3 + ")";
document.getElementById('output1').innerHTML = "<br>Final Stack (P1: " + p1 + "P2: " + p2 + "P3: " + p3 + ")<br>";
document.getElementById('output1').innerHTML += '<br>Congratulations! You solved the Towers of Hanoi in ' + moves + ' moves.';
// document.getElementbyId("output2").innerHTML= "Final Stack (P1: " + source + "P2: " + des + "P3: )" + aux;
}
function popNode() {
p1.pop();
//p2.pop();
document.getElementById("output1").innerHTML = p1.toString();
}
//var disc =...