Assignment 1 - Using your JSFiddle account you are going to create a guessing game, only it will be the computer doing the guessing. Here is how it works - the computer will ask you for a number between 1 and 1000, it will check first to make sure your input is within the bounds.
Once you enter the number it will guess the number and do a comparison with the number you entered. It will output the results of the guess and continue to do this until it gets the correct answer. This is what the output of the program will look like (if I enter 329)
Input: 329
Output:
Guessed 500 - too high.
Guessed 250 - too low.
Guessed 375 - too high.
Guessed 313 - too low.
Guessed 344 - too high.
Guessed 329 - Got It!
It took me 6 Tries.
You can probably figure out how my algorithm works, yours should use the same basic logic. You will want to create an algorithm that is efficient (lowest possible O).
Programming parameters:
1 - This will be coded in Javascript.
2 - You should create a dimensioned array of 1000 elements.
3 - You should fill in the elements from 1 to 1000 in order prior to implementing the search
<h1><center>Guessing Game</center></h1>
<h4><center> Enter a number between 1 and 1000</center> </h4>
<input type="output" id="input" value="329">
<button type="button" onclick="guessingGame(createArray,parseInt(document.getElementById('input').value))">Guess!</button>
<br>
<br>
<div id="output"></div>
JavaScript
var createArray = [size];
var size = 1000;
var d = "";
var count = 0;
var input;
var guess
function guessingGame(array, input) {
var min = 0;
var max = size - 1;
for (i = 0; i < size; i++) {
createArray[i] = i + 1;
}
if (input > 0 && input <= size) {
while (array[guess] = input) {
count++;
guess = Math.floor((min + max) / 2);
if (array[guess] < input) {
min = guess + 1;
d += "Guessed " + array[guess] + " - too low.<br>";
} else if (array[guess] > input) {
max = guess - 1;
d += "Guessed " + array[guess] + " - too high.<br>";
} else {
d += "It took me " + array[guess] + " in " + count + " Tries";
document.getElementById("output").innerHTML = d;
d = "";
return guess;
}
}
} else {
d = "Enter a number between 1 and 1000";
}
document.getElementById("output").innerHTML = d;
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.