COP3530 Assignment3

by Kristy Bond

HTML

<h1>COP3530 Search Algorithm</h1>
<!--gather the numerical guess input from the user-->
Welcome to the Guessing Game. Guess a number between 1 and 1,000:
<input type="number" id="userNum" min="0" max="1000" value="100" />
<br/>
<br/>
<!--begin the guessing algorithm with the button click-->
Press here to let me try to guess your number:
<input type="button" value="Guessing Game" id="userGuess" onclick="guessingGame();" />

<!---display results of Guessing Game--->
<div id="2output"></div>
<br/>

<div id="output"></div>

JavaScript

//set global variables

var array = [];

var guesses;

var d = "";

//when the user clicks the button, it starts the function Guessing game.

 

function createArray() {

  //display array with random values

  for (var i = 0; i < 1000; i++) {

    array[i] = i + 1;

  }

}

 

function clearDisplay() {

  document.getElementById("2output").innerHTML = "";

  document.getElementById("output").innerHTML = "";

}

 

 

function guessingGame() {

  var mysteryNum = document.getElementById("userNum").value;

  var high = 1000;

  var low = 0;

 

  clearDisplay();

  createArray();

 

  var guess = 500;

  guesses = 1;

 

  d = "First Guess: " + guess +"<br/>";

  while ((guess != mysteryNum) && (guesses < 100)) {

     if (guess > mysteryNum) {

        high = guess;

        guess = low + Math.floor((guess - low) / 2);

        guesses++;

        d += "Guess number " + guesses + " will be: " + guess +" low: " + low +  " high: " + high + " <br/>";

      

     }

     else if (guess < mysteryNum) {

        low = guess;

        guess = low + Math.floor((high - guess) / 2);

        guesses++;

        d += "Guess number " + guesses + " will be: " + guess  +" low: " + low +  " high: " + high +"<br/>";

       

     }

  }

  d += "Got it on guess " + guesses + "<br/>";

  document.getElementById("output").innerHTML = d;

}

 

//clearing out results from previous Guessing Game to be prepared to start the game over.

function clearDisplay() {

  document.getElementById("2output").innerHTML = "";

  document.getElementById("output").innerHTML = "";

}