Assignment 7 : "Recursion"
by MimiE
HTML
<br/>
Enter the Number of Disks: <input type = " textbox" id="value" value = ""/>
<br/><br/>
<input id="startH" value=" How Many Discs Move" onclick="tHanoi();" /><br/><br/>
<input type = "button" id = calc value = "Calculate the Number of Moves:" onclick = "towerHanoi();"/ >
<br/>
<div id="output"></div>
<div id="output1"></div>
JavaScript
var stack = new Stack();
var count = "";
var Node = function(_data) {
this.next = null;
this.last = null;
this.data = _data;
}
function Stack() {
this.top = null;
this.bottom = null;
this.push = function(_data) {
if (this.bottom == null) {
this.bottom = new Node(_data);
this.top = this.bottom;
return this;
}
var addedNode = new Node(_data);
addedNode.last = this.top;
this.top.next = addedNode;
this.top = addedNode;
this.length++;
return this;
}
this.pop = function() {
var val;
if (this.bottom == null) {
alert("The Stack is Empty");
return null;
}
if (this.bottom === this.top) {
val = this.top;
this.top = null;
this.bottom = null;
return val;
} else {
val = this.top;
this.top = this.top.last;
this.top.next = null;
return val;
}
}
this.toString = function() {
var str = "";
var node = this.bottom;
while (node != null) {
str += node.data + ",";
node = node.next;
}
return str;
}
}
function tHanoi() {
var stackA = new Stack()
var stackB = new Stack()
var stackC = new Stack()
count = 0;
var v = parseInt(document.getElementById("value").value);
for (var h = v; h > 0; h--)
stackA.push(h);
document.getElementById("output").innerHTML = "<br/> Stack A before: " + stackA.toString();
document.getElementById("output").innerHTML += "<br/> Stack B before: " + stackB.toString();
moveHanoi(v, 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/><br/> Towers of Hanoi calculated: " + count ;
}
function moveHanoi(n, A, B, C) {
if (n == 1) {
move(A, B);
count++;
}
else{
moveHanoi(n - 1, A, C, B); //the recursive...