Search code examples
javascriptnumbersgenerator

How to restrict one number in 1-100 auto generate JavaScript


I want to restrict one number for example 34 in this number generator. When someone generates a number with a button click, never coincides with a restricted number for example 34.

function IsNumeric(n) {
    return !isNaN(n);
}
$(function () {
    $("#getit").click(function () {
        let numLow = $("#lownumber").val();
        let numHigh = $("#highnumber").val();

        let adjustedHigh = (parseFloat(numHigh) - parseFloat(numLow)) + 1;

        let numRand = Math.floor(Math.random() * adjustedHigh) + parseFloat(numLow);

        if ((IsNumeric(numLow)) && (IsNumeric(numHigh)) && (parseFloat(numLow) <= parseFloat(numHigh)) && (numLow !== '') && (numHigh !== '')) {
            $("#randomnumber").text(numRand);
        } else {
            $("#randomnumber").text("Careful now...");
        }
        return false;
    });

    let input = $("input[type=text]");
    
    input.each(function () {
        $(this).data("first-click", true);
    });

    input.focus(function () {
        if ($(this).data("first-click")) {
            $(this).val("");
            $(this).data("first-click", false);
            $(this).css("color", "black");
        }
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="page-wrap">
        
        <input type="text" id="lownumber" value="1" />
        
        <input type="text" id="highnumber" value="100" />
        
        <br />
        
        <button id="getit">Generate!</button>
        
        <div id="randomnumber"></div>
    
    </div>


Solution

  • Add a conditional check to make sure the generated number is not the restricted number:

    var numRand = 0, restrictedNumber = 34;      
    do {
        numRand = Math.floor(Math.random()*adjustedHigh) + parseFloat(numLow);
    } while (numRand == restrictedNumber);
    

    http://jsfiddle.net/JHhDx/

    You'll probably also want to add something to check to make sure the restricted number is also not the only possible number