Assignment 7
Tower of Hanoi
by Nyle Anderson
HTML
<p id = "output">
</p>
JavaScript
//Big O notation for tower of Hanoi is O(2^n)
//Moves should equal (2^n)-1
var Node = function(_content) {
this.above=null;
this.below=null;
this.content=_content;
}
var Stack = function() {
this.top=null;
this.height = 0;
}
Stack.prototype.push = function(_content) {
var n = new Node(_content);
if (this.top == null) {
this.top = n;
this.height++;
return;
}
this.top.above = n;
n.below = this.top;
this.top = n;
this.height++;
}
Stack.prototype.pop = function() {
if (this.top == null) return null;
if (this.top.below == null) {
var temp = this.top;
this.top = null;
return temp;
}
var temp = this.top;
this.top.below.above = null;
this.top = this.top.below;
return temp;
}
Stack.prototype.asString = function(){
if (this.top == null) return "Empty";
var s = "";
var n = this.top;
while (n != null) {
s += n.content + " : <br>";
n = n.below;
}
return s;
}
//create the stacks
var stack = new Stack();
Stack.protoype.push('disk1');
Stack.prototype.push('disk2');
Stack.prototype.push('disk3');
var stack2 = new Stack();
var stack3 = new Stack();
function addToStack() {
var c = document.getElementById("value").value;
stack.push(c);
document.getElementById("output").innerHTML = stack.asString();
}
function popFromStack() {
stack.pop();
document.getElementById("output").innerHTML = stack.asString();
}
//the move function
function Hanoi(n, stack, stack3, stack2){
if(n == 0) return;
Hanoi(n-1, stack, stack2, stack3);
move(stack1,stack3);
Hanoi(n-1, stack2, stack3, stack);
}
Hanoi();