Choose a number between 1 and 1000:
<br/>
<br/>
<input type="textbox" id="value" number="" />
<input type="button" id="button1" value="Run Program" onClick="searchArray();" />
<br/>
<br/>
<div id="output">
</div>
JavaScript
var array = new Array(1000);
var display = "";
function fillArray() {
for (var i = 0; i < array.length; i++) {
array[i] = i + 1;
}
}
function searchArray() {
clearDisplay();
var min = 0;
var max = 999;
var guessCount = 0;
var potential = Math.floor((max + min) / 2);
var actual = parseInt(document.getElementById('value').value);
// TRY TO GET A TYPEOF (typeof "John" returns string) TO WORK FOR OTHER NON VALID ANSWERS
// POSSIBLY LOOK INTO NON VALUE ANSWERS THAT CRASHES THE PROGRAM
if (actual < 1 || actual > 1000) {
display = actual + " is not valid. Pick a numbet from 1 to 1000";
document.getElementById("output").innerHTML = display;
} else {
while (array[potential] != actual) {
if (array[potential] < actual) {
//LOOKING AT LOW CASE
display += "Guessed " + array[potential] + " - Too low. <br/>";
document.getElementById("output").innerHTML = display;
min = potential + 1;
potential = Math.round((max + min) / 2);
} else {
//LOOKING AT HIGH CASE
display += "Guessed " + array[potential] + " - Too high. <br/>";
document.getElementById("output").innerHTML = display;
max = potential - 1;
potential = Math.round((max + min) / 2);
}
guessCount++;
}
guessCount++;
//FINAL PORTION
display += "Guessed " + array[potential] + " - Just right. <br/><br/>" +
"This program took " + guessCount + " tries to obtain the correct answer.";
document.getElementById("output").innerHTML = display;
}
}
fillArray();
function clearDisplay() {
display = "";
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.