JSFiddle - React, Tailwind, and code Playground

by Francisco Guerra

HTML

Pick a number between 1 and 1000:
<input type = "textbox" id = "value" number = "" />
<input type = "button" id = "button1" value = "Guess" 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 = 1;
  var max = 1000;
  var guessCount = 1;
  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 me " + guessCount + " Tries."
		document.getElementById("output").innerHTML = d;
	}
  }

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