Towers of Hanoi Example

fork of RPN calculator

by Ron Eaglin

HTML

Please enter the number of disks: <input id='uInput' type='textbox' value="5"><br><br>

<button id=calc onClick='run()'>Calculate number of moves</button>

<div id='output1'>
</div>

JavaScript

var num = 0;

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) {
    // No head - create one
    if (this.bottom == null) {
      this.bottom = new Node(_content);
      this.top = this.bottom;
      return this;
    }

    var addedNode = new Node(_content);
    addedNode.last = this.top; // pointer to previous node
    this.top.next = addedNode; // current top points to new
    this.top = addedNode; // which becomes new top
    return this;
  }

  this.pop = function() {
    if (this.bottom == null) {
      alert("The Stack is Empty");
      return null;
    }
    // Case of one node
    if (this.bottom == this.top) {
      var n = this.top;
      this.top = null;
      this.bottom = null;

      return n;
    }

    // Now remove top Node
    var a = this.top; // hold value for return
    this.top = this.top.last;
    this.top.next = null;

    return a;
  }

  this.toString = function() {
    var str = "";
    var node = this.bottom;

    while (node != null) {
      str += node.content + ":";
      node = node.next;
    }
    return str;
  }
}



function run() {
  var stackA = new Stack();
  var stackB = new Stack();
  var stackC = new Stack();

  // Fill Original Stack
  var i = parseInt(document.getElementById('uInput').value);
  for (var t = i; t > 0; t--) {
    stackA.push(t);
  }

  document.getElementById('output1').innerHTML = '<br/>Stack A Before: ' + stackA.toString();
  document.getElementById('output1').innerHTML += '<br/>Stack B Before: ' + stackB.toString();


  runHanoi(i, stackA, stackB, stackC);

  document.getElementById('output1').innerHTML += '<br/>Stack A After: ' + stackA.toString();
  document.getElementById('output1').innerHTML += '<br/>Stack B After: ' + stackB.toString();


  document.getElementById('output1').innerHTML += '<br/><br/>Congratulations! You solved the Towers of Hanoi...