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 = "";
}
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.