JSFiddle - React, Tailwind, and code Playground

by hesster92

HTML

Tower of Hanoi
<br><br> Enter Number of Disks: <input type="textbox" id="tbSize" value="5">
<br><br>
<input type="button" id="btnSolve" value="Solve!" onclick="solve()">
<br><br> Number of moves to solve Tower of Hanoi:
<p id="output">

JavaScript

Stack = function() {
  this.head = null;
  this.size = 0;
}

Node = function(_content) {
  this.content = _content;
  this.next = null;
}

Stack.prototype.push = function(_content) {
  var node = new Node();
  node.content = _content;
  if (this.head) {
    node.next = this.head;
    this.head = node;
  } else {
    this.head = node;
  }
  this.size++;
}

Stack.prototype.pop = function() {
  if (this.head) {
    var popped = this.head;
    this.head = this.head.next;
    this.size--;
    return popped.content;
  } else {
    console.log("There is nothing in the stack");
    return false;
  }
}

Stack.prototype.toString = function() {
  var s = "";
  var node = this.head;

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

var n = 0;

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

  n = 0;

  var i = parseInt(document.getElementById("tbSize").value);
  for (var t = i; t > 0; t--) {
    stackA.push(t);
  }

  document.getElementById("output").innerHTML = "<br>Stack A Before: " + stackA.toString();
  document.getElementById("output").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.getElementById("output").innerHTML += "<br>Congratulations! You solved the Towers of Hanoi in " + n + " moves.";
}


function runHanoi(z, A, B, C) {
  if (z == 1) {
    move(A, B);
    n++;
  } else {
    runHanoi(z - 1, A, C, B);
    move(A, B);
    n++;

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

function move(A, B) {
  B.push(A.pop());
}