var arrayOutput = new Array();
document.getElementById("btnPress").onclick = function() {submitMyNumber()};
function submitMyNumber() {
var submittedNumber = 0;
var submittedNumber = document.getElementById("number").value;
array = new Array(1000);
for (var i = 0; i < 1000; i++){
array[i] = i + 1;
}
// If else loop
if (submittedNumber > 1 && submittedNumber <= 1000) {
arrayOutput = new Array();
searchArray(array, submittedNumber);
document.getElementById("guessTheNumber").innerHTML = arrayOutput.join("<br>");
}
else {
document.getElementById("guessTheNumber").innerHTML = "You entered " + submittedNumber + " Please enter a number between 1 and 1000"
}
}
//function for the computer to search for the number
function searchNumber(array, correctNumber) {
var min = 0;
var max = array.length -1;
var times = 0;
var guess;
//while
while (min <= max) {
guess = Math.floor((max + min) / 2);
//if
if (array[guess] == correctNumber) {
arrayOutput.push("Guessed" + array[guess] + " - Got it!");
arrayOutput.push("It took " + array[times] + " times.");
return guess;
}
//else if
else if (array[guess] < correctNumber) {
times++;
arrayOutput.push("Guessed" + array[guess] + "- too low.");
min = guess + 1;
}
//else
else {
times++;
arrayOutput.push("Guessed" + array[guess] + " - too high.");
max = guess - 1;
}
}return -1;
};
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.