JSFiddle - React, Tailwind, and code Playground

by Peyton Hessler

HTML

<p>Enter a number between 1 and 1000</p>
<input type="text" id="number" value="1"></input>
<button type="button" onclick="Main()">Start Guessing</button>
<div id="text"></div>

JavaScript

var TextOut = "";
    var dArray = [];
    var Main = function() {
        TextOut = "";
        var inNum = document.getElementById('number').value;

        //Load the array with ordered number 1 to 1000
        loadArray();

        //Run the functions and look for the number
        var result = doSearch(dArray, inNum);

        //Output final result
        document.getElementById('text').innerHTML = TextOut;

    }

    // Load the array with ordered numbers 1 to 1000
    var loadArray = function() {
        for (i = 0; i < 1000; i++) {
            dArray[i] = i + 1;
        }
    }

    //Get number from use and have comptuer guess until it finds it
    var doSearch = function(array, targetValue) {
        var min = 0;
        var max = array.length;
        var guess;
        var count = 1;
        if (targetValue >= 1 && targetValue <= 1000) {
            while (max >= min) {
                guess = Math.floor((min + max) / 2);
                if (array[guess] == targetValue) {
                    TextOut += "<BR>" + guess + " is your number!";
                    TextOut += "<BR> It took " + count + " times to guess the number"
                    return;
                } else if (array[guess] < targetValue) {
                    min = guess + 1;
                    TextOut += "<BR>" + guess + " is too low";
                    count = count + 1;
                } else {
                    max = guess - 1;
                    TextOut += "<BR>" + guess + " is too high";
                    count = count + 1;
                }
            }
        } else {
            alert("Invalid Input");
        }
        return;
        alert(guess);
    }