JSFiddle - React, Tailwind, and code Playground

by zazagalaxy

HTML

Please enter the number of disks: <input id='uInput' type='textbox' value=''><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(_desc) {
this.desc = _desc;
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) {
return null;
}
// Case of one node
if (this.bottom == this.top) {
this.bottom = this.top;
return this.top.content;
}

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

return a.content;
}
}

Stack.prototype.toString = function() {
var str = this.desc + ": ";
var node = this.bottom;

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


var num = 0;

var run = function() {
var stackA = new Stack("A");
var stackB = new Stack("B");
var stackC = new Stack("C");
//var num = 0;
//Populate stackA
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 in ' + num + ' moves. ';
}

function runHanoi(z, A, B, C) {
//Base Condition
if (z == 0){
return;
}else if (z == 1) {
move(A, B);
num++;
} else {
// Recursive Call
runHanoi(z -...