COP3530 Search Algorithm

Create guessing game, computer will be doing the guessing. Computer asks for a number between 1 and 1000, computer will check the bounds of the input and make several attempts to guess the correct answer.

by Neil Daley

HTML

<div id= "container">
  Enter a number for the computer to guess:
  <br/><br/>
  <input type= "button" id= "guess" value= "Guess the Number" style= "color:white; background-color:blue" onClick= "guessNum();" />
  <input type= "textbox" id= "number" value= ""/>
  <br/>
  <div id= "output">
    
  </div>
</div>

JavaScript

var array = [];
var min = 0;  // Minimum array value
var max = 1000;  // Maximum array value
var c = 0;  // Attempts counter
var o = "";  // Output area
var m = 500;  // Midpoint value

function guessNum() {
	var a = parseInt(document.getElementById("number").value);
  
  // Check within array parameter
  if (a < 1 || a > 1000)
  	{	
    	// Error message
    	o = "Enter a number between 1 and 1000, please try again."
      clearDisplay();    // Clears textbox
    }	else	{
    	createArray();
    	if (m < a)	{
      	c++;             // Attepmts counter increments
        o += 'Guessed ' + m + ' - too low. <br/>';
        displayResult();
        min = m;         //Midpoint to minmum value comparison
        m = Math.round((min + max) / 2);
        
        guessNum();
      }	else if (m > a) {
      	c++;
        o += 'Guessed ' + m + ' - too high. <br/>';
        displayResult();
        max = m;
        m = Math.round((min + max) / 2);
        
        guessNum();
      } else if (m == a) {
      	c++;
        o += 'Guessed ' + m + ' - Got it! :) <br/><br/>' + 'It took me ' + c + ' tries.';
        displayResult();
      }
    }
}

function displayResult() {
	document.getElementById("output").innerHTML = o;
}

function clearDisplay() {
	document.getElementById("output").innerHTML = o;
  var c = 0;
   o = "";
 // guessNum();
}

function createArray() {
	for (var i = 0; i < 1000; i++) {
    array[i] = i + 1;
    }
}