<html>
<body>
<fieldset>
<legend>Inputs</legend>
Enter a number from 1 to 1000<br>
<input type="number" id="tbValue" min="0" max="1000" value= "500"><br>
<input type="button" value="Guess" id= "btGuess">
</fieldset>
<fieldset>
<legend>Outputs</legend>
<div id='output1'></div><br><br>
<div id='output2'></div>
</fieldset>
</body>
</html>
JavaScript
var Array = [];
var d = "";
var size = 1000;
var numGuess = document.getElementById("tbValue").value;
document.getElementById("btGuess").onclick = function() {
CheckPerimeter();
};
function CreateArray(){
ClearArray();
for (var i = 0; i < size; i++){
Array[i]= i + 1;
}
}
function ClearArray(){
d = "";
document.getElementById("output1").innerHTML= "";
document.getElementById("output2").innerHTML="";
}
function CheckPerimeter() {
ClearArray();
numGuess = document.getElementById("tbValue").value;
if (numGuess < 1) {
d += "The number you entered is too low. Please enter a number between 1 and 1000.";
document.getElementById('output1').innerHTML = d;
return;
} else if (numGuess > size) {
d += "The number you entered is too high. Please enter a number between 1 and 1000.";
document.getElementById('output1').innerHTML = d;
return;
} else {
BinarySearch();
}
}
function BinarySearch(){
ClearArray();
CreateArray()
var totGuess = 0;
var start = 1;
var end = size;
var mid;
numGuess = document.getElementById("tbValue").value;
while (mid != numGuess) {
mid = Math.floor((start + end) / 2);
if (numGuess < mid){
d += "<div>Guessed " + mid + "- Too high.</div>";
end = mid;
mid = Math.floor((start + end) / 2);
totGuess++;
} else if (numGuess > mid) {
d += "<div> Guessed " + mid + "- Too low.</div>";
start = mid;
mid = (Math.floor((start + end) / 2));
totGuess++
}
}
d += "<div>Guessed " + mid + "- Got it!</div>";
totGuess++;
document.getElementById('output1').innerHTML = "<div>It took " + totGuess + " guesses to match your number.</div>";
document.getElementById('output2').innerHTML = d;
}
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.