Lasha
Lasha

Reputation: 625

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>

Upvotes: 2

Views: 5678

Answers (2)

chucknelson
chucknelson

Reputation: 2336

Besides a loop, you could also make a recursive function.

http://jsfiddle.net/chucknelson/eYAy6/2/

var userRestrictedNum = 34; //could get this from input    

function getit(restrictedNum) {
        ...random number code...

        if(numRand != restrictedNum) {
            return numRand;
        }
        else {
            return getit(restrictedNum);
        }
    }

    $("#getit").click(function() {
        $("#randomnumber").text(getit(userRestrictedNum));
    });

Upvotes: 1

Matthew Mcveigh
Matthew Mcveigh

Reputation: 5685

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

Upvotes: 4

Related Questions