Javascript Algorithm Hanoi tower

Description

Javascript Algorithm Hanoi tower

function Stack() {
  var top = null;

  function createItem(data) {
    var prev = null;

    function getData() {
      return data;
    }//  w  w  w  . j  a va 2 s.  co m

    function getPrev() {
      return prev;
    }

    function setPrev(item) {
      prev = item;
    }

    return {
      getData: getData,
      getPrev: getPrev,
      setPrev: setPrev
    };
  }

  function push(data) {
    if (top === null) {
      top = createItem(data);
    }
    else {
      var newItem = createItem(data);
      newItem.setPrev(top);
      top = newItem;
    }
  }

  function pop(callback) {
    var err = null,
      value = null;
    if (top === null) {
      err = "Underflow";
    }
    else {
      value = top.getData();
      top = top.getPrev();
    }
    if (callback) {
      callback(err, value);
    }
  }

  function printStack() {
    var currTop = top;
    var result = [];
    while (currTop !== null) {
      result.unshift(currTop.getData());
      currTop = currTop.getPrev();
    }
    console.log(JSON.stringify(result));
  }

  return {
    push: push,
    pop: pop,
    printStack: printStack
  };
}

module.exports = Stack;

var test = function(err, value) {
  console.log("The err is: " + err);
  console.log("The value is: " + value);
};


var Hanoi = function(disk, source, dest, spare) {
  source.printStack();
  dest.printStack();
  spare.printStack();

  if (disk === 0) {
    source.pop(function(err, value) {
      dest.push(value);
    });
  }
  else {
    Hanoi(disk - 1, source, spare, dest);
    source.pop(function(err, value) {
      if (value !== null) {
        dest.push(value);
      }
    });
    Hanoi(disk - 1, spare, dest, source);
  }
};

var source = Stack();
var spare = Stack();
var dest = Stack();

source.push("----");
source.push("---");
source.push("--");
source.push("-");

console.log("=================");
console.log("Start of hanoi");
console.log("=================");

source.printStack();

Hanoi(4, source, dest, spare);

console.log("RESULT");
console.log("source:");
source.printStack();
console.log("spare:");
spare.printStack();
console.log("dest:");
dest.printStack();



PreviousNext

Related