We are going to solve the classic Tower of Hanoi. Using the wikipedia article I want you to write a computer program that calculates the number of moves necessary to solve Tower of Hanoi given a number of disks. There are formulas that calculate this - you are NOT going to use them. You will calculate by going through the recursive algorithm of the tower and counting every time a block is moved.
Answer the following questions in the interface of your code;
1. What is the Complexity (In Big O)?
2. Should we be concerned with concerned with the legend of the world ending when the 64 disk solution is physically solved it it takes 2 seconds for each move?
<h1><center> Module 6</center></h1>
<h3><center> Recursions</center></h3>
<h4><center>The complexity of the Tower of Hanoi is 2^(n - 1) and 2(-2^n) </center></h4> Should we be concerned with concerned with the legend of the world ending when the 64 disk solution is physically solved it it takes 2 seconds for each move? No
<div>
<br> Number of Disks
<br>
<input type="textbox" id="disks" value="3" onclick="displayResults()">
<br>
<input type="button" value="Start" onClick="numberOfMoves();" />
<p id='output'></p>
JavaScript
function results() {
document.getElementById("output").innerHTML = "";
}
function TowerofHanoi(disks) {
var count = 1;
for (var a = 1; a <= disks; ++a) {
count = count * 2;
}
return (count - 1);
}
function numberOfMoves() {
var numOfDisks = parseInt(document.getElementById("disks").value);
if (numOfDisks < 1) {
document.getElementById("output").innerHTML = "Please enter a number greater than zero";
} else if (!Number.isInteger(numOfDisks)) {
document.getElementById("output").innerHTML = "Please enter a valid number";
} else {
document.getElementById("output").innerHTML = "It took " + TowerofHanoi(numOfDisks) + " moves to complete the Tower of Hanoi " + numOfDisks + " disks";
}
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.