<!--textbox for user to enter value with placeholder-->
<b>Please Enter a number:</b><br>
<input type="text" id="number" placeholder="# between 1 and 1000" /><br><br>
<!--Click for my guess button-->
<input type="submit" id="btnPress" value="Click for my guess" /><br><br>
<div id="guessTheNumber"></div>
//Globalized to use in many functions
var outputarray = new Array();
//My onclick function for my HTML button
document.getElementById("btnPress").onclick = function() {submitNumber()};
//New function for submitted values
function submitNumber() {
//gets the number the user enters
var submittedNumber = document.getElementById("number").value;
//Putting numbers between 1 and 1000 into an array
array = new Array(1000);
for (var i=0; i < 1000; i++){
array[i] = i+1;
}
//if submitted number is greater than 0 AND less than or equal 1000 its findable if not error message.
if (submittedNumber > 0 && submittedNumber <= 1000) {
outputarray = new Array();
doSearch(array, submittedNumber);
document.getElementById('guessTheNumber').innerHTML = outputarray.join("<br>");
}
else {
document.getElementById('guessTheNumber').innerHTML = "You entered " + submittedNumber + " Please enter a number between 1 and 1000"
}
}
//New function computer searching the array for the submitted number
function doSearch(array, correctNumber) {
var min = 0;
var tries = 0;
var max = array.length - 1;
var guess;
while(min <= max) {
guess = Math.floor((max + min) / 2); //first guess will always be 500
if (array[guess] == correctNumber) {
outputarray.push("Guessed "+ array[guess] + " = Got it!");
outputarray.push("I Guessed it in " + array[tries] + " tries.");
return guess;
}
else if (array[guess] < correctNumber) {
tries++;
outputarray.push("Guessed " + array[guess] + " = My guess was too low.");
min = guess + 1;
}
else {
tries++;
outputarray.push("Guessed " + array[guess] + " = My guess was too high.");
max = guess - 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.