<p>Enter a number between 1 and 1000</p>
<input type="text" id="number" value="1"></input>
<button type="button" onclick="Main()">Start Guessing</button>
<div id="text"></div>
JavaScript
var TextOut = "";
var dArray = [];
var Main = function() {
TextOut = "";
var inNum = document.getElementById('number').value;
//Load the array with ordered number 1 to 1000
loadArray();
//Run the functions and look for the number
var result = doSearch(dArray, inNum);
//Output final result
document.getElementById('text').innerHTML = TextOut;
}
// Load the array with ordered numbers 1 to 1000
var loadArray = function() {
for (i = 0; i < 1000; i++) {
dArray[i] = i + 1;
}
}
//Get number from use and have comptuer guess until it finds it
var doSearch = function(array, targetValue) {
var min = 0;
var max = array.length;
var guess;
var count = 1;
if (targetValue >= 1 && targetValue <= 1000) {
while (max >= min) {
guess = Math.floor((min + max) / 2);
if (array[guess] == targetValue) {
TextOut += "<BR>" + guess + " is your number!";
TextOut += "<BR> It took " + count + " times to guess the number"
return;
} else if (array[guess] < targetValue) {
min = guess + 1;
TextOut += "<BR>" + guess + " is too low";
count = count + 1;
} else {
max = guess - 1;
TextOut += "<BR>" + guess + " is too high";
count = count + 1;
}
}
} else {
alert("Invalid Input");
}
return;
alert(guess);
}
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.