Assignment 7
by leiperte
HTML
Please enter the number of disk: <input id='uInput' type="textbox" value='5'>
<br><br>
<button id='calc' onClick="run()">
Calculate number of moves
</button>
<div id="output">
</div>
JavaScript
//Assignment 7
//Complexity in Big O is O(2n)
//Don't be concerned, as it will take 584+ billion years for the monks to complete a Tower of Hanoi with 64 disk. Be more concerned with the sun dying first.
//Stack code copied from assignment 5
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) {
var node = new Node();
node.content = content;
node.next = null;
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) {
this.top = this.bottom;
this.top.last = null;
return this;
}
var c = this.top;
this.top = this.top.last;
this.top.next = null;
return c;
}
}
Stack.prototype.toString = function() {
var str = "";
var node = this.bottom;
while (node != null) {
str += node.content + " ";
node = node.next;
}
return str;
}
//new code for assignment 7
var num = 0;
function run() {
var stackA = new Stack();
var stackB = new Stack();
var stackC = new Stack();
//fill original stack
var i = parseInt(document.getElementById("uInput").value);
if (i > 7) {
document.getElementById("output").innerHTML = "Please enter a number less than or equal to 7.";
return null;
} else {
for (var t = i; t > 0; t--) {
stackA.push(t);
}
}
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);
...