var outputarray = new Array();
//when 'Guess' is clicked call myFormSubmit function
document.getElementById("click").onclick = function() {myFormSubmit()};
//form function called and stores form input as variables
function myFormSubmit() {
var number_entered = 0;
var number_entered = document.getElementById("number").value;
array = new Array(1000);
for (var i=0; i < 1000; i++){// fill array with numbers 1-1000
array[i] = i+1;
} //document.getElementById('test').innerHTML = array;
//call array function and display it in the updated array div
if (number_entered > 1 && number_entered <= 1000) {
outputarray = new Array();
doSearch(array, number_entered);
document.getElementById('guess-results').innerHTML = outputarray.join("<br>");
}
else {
document.getElementById('guess-results').innerHTML = "You entered " + number_entered + " Please enter a number between 1 and 1000"
}
}
//var doSearch = function(array, targetValue) {
function doSearch(array, targetValue) {
var min = 0;
var tries = 0;
var max = array.length - 1;
var guess;
while(min <= max) {
guess = Math.floor((max + min) / 2);
if (array[guess] == targetValue) {
outputarray.push("Guessed "+ array[guess] + " - Got it!");
outputarray.push("It took " + array[tries] + " tries.");
return guess;
}
else if (array[guess] < targetValue) {
tries++;
outputarray.push("Guessed " + array[guess] + " - too low.");
//console.log(" too low " + array[guess]);
min = guess + 1;
}
else {
tries++;
outputarray.push("Guessed " + array[guess] + " - too high.");
//console.log(" too high " + array[guess]);
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.