Search code examples
javascriptbinary-search

Create a guessing game, where the computer guesses the number that the user inputs


Given that user input should be between 1 and 1000, I'm trying to use a binary search of a (sorted) integer array of 1-1000 to output the following:

enter image description here

I just want the output--ignore the formatting. Now, the code:

const testButton = document.getElementById("test");

testButton.addEventListener('click', () => {
  myArray = new Array(1000);
  for (i = 0; i < 1000; i++) {
    myArray[i] = i + 1;
    //just for visual aid, not to be actual part of final output
    document.getElementById("boop").innerHTML = myArray;
    document.getElementById("boop").innerHTML += `<p>${myArray[myArray.length -1]}</p>`;
  }


  var userInput = parseInt(document.getElementById("input").value);
  let min = myArray[0];
  let max = myArray[myArray.length - 1];

  if (userInput < 1 || userInput > 1000) {
    document.getElementById("boop").innerHTML += "That's not between 1 and 1000.";
  } else {

    while (min < max) {

      userInput = parseInt(document.getElementById("input").value);
      let min = myArray[0];
      let max = myArray[myArray.length - 1];


      let mid = myArray[myArray.length - 1];

      mid = parseInt(Math.floor(mid / 2));
      let count = 0;

      if (userInput == mid) {
        count++;
        document.getElementById("boop").innerHTML += `<p>Guessed ${mid} and got it. Took me ${count} tries.</p>`;
      } else if (userInput > mid) {
        count++;
        document.getElementById("boop").innerHTML += `<p>Guessed ${mid}. Too low.</p>`;
        min = mid + 1;
        mid = parseInt(Math.floor(mid + (mid / 2)));
      } else {
        count++;
        document.getElementById("boop").innerHTML += `<p>Guessed ${mid}. Too high.</p>`;
        max = mid - 1;
        mid = parseInt(Math.floor(mid / 2));
      }
    }

  }


});
<html>

<head>
</head>

<body>
  <input type="text" id="input">
  <button id="test">
Start Game
</button>
  <p id="boop">
  </p>
</body>

</html>

If you'd like to mess with my JSfiddle, enter link description here

I don't receive any console errors when running it, but it does appear to be an infinite loop because my browser hangs. I've looked through similar questions, and the most similar I can find is: enter link description here but it's using Java, and I haven't learned Java (still pretty new to programming in general), so it's a bit confusing, but I believe it's a similar concept.

Thank you in advance for any help you can offer!


Solution

  • I have updated the JSfiddle https://jsfiddle.net/y4ta13es/

    The infinite loop was because of the while condition never exiting since the condition always evaluated to true.

    Most of your code was correct with some minor logic flaws, like you are defining the variables inside the while loop. You should declare them outside else the values would never be updated.

    Here is the snippet

     while (min < max) {
        index = parseInt((max+min)/2);
          let mid = myArray[index];
          if (userInput == mid) {
            count++;
            document.getElementById("boop").innerHTML += `<p>Guessed ${mid} and got it. Took me ${count} tries.</p>`;
            break;
          } else if (userInput > mid) {
          min = index;
            count++;
            document.getElementById("boop").innerHTML += `<p>Guessed ${mid}. Too low.</p>`;
          } else {
             max = index;
            count++;
            document.getElementById("boop").innerHTML += `<p>Guessed ${mid}. Too high.</p>`;
          }
        }