JSFiddle - React, Tailwind, and code Playground
by wooozy
HTML
<p>Input Numbers from (1-15): <input type="text" id="theNum" style="width:30px;"/></p>
<input type="button" onclick="guess()" value="Enter" /><br><br>
Output: <br /><br />
<textarea id="output" name="output" style="width:100px; height:150px;"></textarea>
JavaScript
function guess()
{
var size = Number(document.getElementById("theNum").value);
if (size > 0 && size % 1 === 0)
{
var array = new Array(size);
var outputGuesses = document.getElementById("output");
outputGuesses.value= "Number of Guesses";
for (i = 0; i < array.length; i++) {
array[i] = i + 1;
}
for (var n = 0; n <array.length; n++){
var min = 0;
var max = array.length - 1;
var index;
var guessCompute;
var theNum = array[n];
var count = 0;
if (theNum <= 15 && theNum > 0)
{
while (min <= max)
{
count = count + 1;
index = Math.floor((min + max) / 2);
guessCompute = array[index];
if (guessCompute < theNum)
{
min = index + 1;
count = count + 1;
}
else if (guessCompute > theNum)
{
max = index - 1;
count = count + 1;
}
else
{
outputGuesses.value = outputGuesses.value + "\r\r" + " " + n + ": "+ count;
min = max + 1;
}
}
}
else
{
outputGuesses.value = "Please input a number from (1-15)";
}
}
}
else
{
alert("Please input a Number from (1-15)");
}
}