Assignment 3: "Searching Algorithm"

by MimiE

HTML

Enter a number between 1 and 1000:
<input type = "textbox" id = "number" value = "" />
<br/>
<br/>

<input type = "button" value = "Check your Guess" 
onclick = "checkGuess();"/>
<br/>
<br/>

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

JavaScript

var array = new Array(1000);
var d = "";
var count = "";
function clearDisplay() 
{
	d = "";
}

function fillArray()
{

  for (var i = 0; i < array.length; i++)
  {
   		array[i] = i+1;
  }
}

function checkGuess()
{

 	clearDisplay();
  
	var n = parseInt(document.getElementById('number').value);
 document.getElementById("output").innerHTML = d;
 count = 0;
 
    if (n < 1 || n > 1000 || isNaN(n))
	{
  	alert('Please enter a number between 1 and 1000.');
    return;
	}
  
		else
		{
			var min = 0;
			var max = array.length - 1;
			var guess = Math.floor((min + max)/2);
			while(array[guess] != n)
			{
				if(array[guess] < n)
				{
					d += "Your Guess is: " + n + " Too low, try again!</br>";	
					min =  guess + 1;
					guess = Math.floor((min + max)/2);
          count++;
				}
				else
        		{     
					d += "Your Guess is: " + n + " Too high, try again!</br>";
					max =  guess - 1; 	
					guess = Math.floor((min + max)/2);
          count++;
        		}
        
			}
			d += "Congratulations! The Guess " + (guess+1) + " is correct!! It took " + count + " guesses.";
			document.getElementById("output").innerHTML = d;
      }
    
}

fillArray();