Question: I am having trouble with creating a code in JScript that will let a user input a number between 1 and 100, have an array
I am having trouble with creating a code in JScript that will let a user input a number between 1 and 100, have an array and have the computer guess and display each guess and number of attempts when done. Not sure how to make a random integer bewteen the new numbers when a guess has been chosen.. Has to work with JSFiddle
Sample Output would be
User typed 256
------------------------
Computer guessed 150 which is too low
Computer guessed 352 which is too high
computer guessed 300 which is too high
computer guessed 256 and guessed correct and it took 4 attempts
HTML
Please input a number
JAVASCRIPT
var array = []; var min=0; var max=100;
var message = "Guess a number between 1 and 100";
var yourGuess = parseInt(document.getElementById("yourGuess").value);
function createArray() {
for (i = min, i <= max, i++){ var array[i]=i; } }
function guessGame(array, yourGuess) {
var count = 0; document.write(message); createArray();
while (array[comGuess] != yourGuess) {
var comGuess = Math.floor((max + min) / 2); count = count + 1; if (array[comGuess] < yourGuess) { message = "Computer guessed " + comGuess + " and is too LOW. "; document.write(message); min = comGuess;
} else if (array[comGuess] > yourGuess) { message = "Computer guessed " + comGuess + " and is too HIGH. "; document.write(message); max = comGuess; } else if (comGuess === yourGuess){ return comGuess; } } message= "I finally found your number! It is " + comGuess + " and it took me " + count + " guesses. "; document.write(message); }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
