JSFiddle - React, Tailwind, and code Playground

by dhizzybusy

HTML

<input id='uinput' type='textbox' value="5"><br>
<button id=calc onclick='run()'>Calculate number of moves</button>
<div id='output1'>
</div>

JavaScript

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(_conent) {

      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) {
    var n = this.top;
    this.top = null;
    this.bottom = null;

    return n;
  }

  var a = this.stop;
  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;
  }
}

function run() {

  var stackA = new Stack();
  var stackB = new Stack();
  var stackC = new 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('output').innerHTML += 'br/>Stack A after:' + stackA.toString();
document.getElementById('output').innerHTML += 'br/>Stack B after:' + stackB.toString();

document.getElementId('output1').innerHTML += '<br/><br/> Congrats!You Solved Tower of Hanoi in ' + num + ' moves.';


function runHanoi(z, A, B, C) {

  if (z == 1) {
    move(A, B);
    num++;
  } else {

    runHanoi(z - 1, A, C, B);

    move(A, B);
    num++;

    runHanoi(z - 1, C, B, A);
  }
}

function move(A, B) {

  B.push(A.pop().content);
}