JSFiddle - React, Tailwind, and code Playground

by Francisco Guerra

HTML

Input a number between 1 and 1000:
<br/>
<br/>
<input type="textbox" id="value" number="" />
<input type="button" id="button1" value="Generate" onClick="searchArray();" />
<br/>
<div id="output">
</div>

JavaScript

var array = new Array(1000);
var d = "";

function createArray() {
  var n = 1;
  for (var i = 0; i < array.length; i++) {
    array[i] = n;
    n++;
  }
}
createArray();

function searchArray() {
  clearDisplay();

  var min = 0;
  var max = 999;
  var guessCount = 0;
  var compGuess = Math.floor((max - min) / 2);
  var guess = parseInt(document.getElementById("value").value);

  if (guess < min || guess > max) {
    d = guess + " is not in range. Pick a number between 1 and 1000."
    document.getElementById("output").innerHTML = d;
  } else {
    while (array[compGuess] != guess) {
      if (array[compGuess] < guess) {
        d += "Guessed " + array[compGuess] + " - Too low. <br/>"
        document.getElementById("output").innerHTML = d;
        min = compGuess;
        compGuess = Math.floor((max + min) / 2);
      } else {
        d += "Guessed " + array[compGuess] + " - Too high.<br/>"
        document.getElementById("output").innerHTML = d;
        max = compGuess;
        compGuess = Math.floor((max + min) / 2);
      }
      guessCount++;
    }
    d += "Guessed " + array[compGuess] + ". Got it! <br/> It took  " + guessCount + " Tries."
    document.getElementById("output").innerHTML = d;
  }
}

function clearDisplay() {
  d = "";
  document.getElementById("output").innerHTML = "";
}