Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript generate random number except some values

Tags:

javascript

I'm generating random numbers from 1 to 20 by calling generateRandom(). How can I exclude some values, say 8 and 15?

function generateRandom(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

var test = generateRandom(1, 20)
like image 647
DevEx Avatar asked Dec 10 '14 16:12

DevEx


People also ask

How to create random numbers in JavaScript?

JavaScript Random 1 Math.random (). Math.random () always returns a number lower than 1. 2 JavaScript Random Integers. Math.random () used with Math.floor () can be used to return random integers. There is no... 3 A Proper Random Function. As you can see from the examples above, it might be a good idea to create a proper random... More ...

How to return a random number between Min and Max in JavaScript?

This JavaScript function always returns a random number between min (included) and max (excluded): Example. function getRndInteger (min, max) {. return Math.floor(Math.random() * (max - min) ) + min; }.

How to generate random number between 0 and 5 in Excel?

Method 1: Using Math.random () function: The Math.random () function is used to return a floating-point pseudo-random number between range [0,1) , 0 (inclusive) and 1 (exclusive). This random number can then be scaled according to the desired range. Example 1: This example generate an integer random number between 1 (min) and 5 (max).

What is math random ()?

Math.random () is an ES1 feature (JavaScript 1997). It is fully supported in all browsers: A number representing a number from 0 up to but not including 1.


3 Answers

it should be or instead of and

function generateRandom(min, max) {
    var num = Math.floor(Math.random() * (max - min + 1)) + min;
    return (num === 8 || num === 15) ? generateRandom(min, max) : num;
}

var test = generateRandom(1, 20)
like image 99
Anas Jame Avatar answered Oct 04 '22 16:10

Anas Jame


One way, which will maintain the generator's statistical properties, is to generate a number in [1, 18]. Then apply, in this order:

  1. If the number is 8 or more, add 1.

  2. If the number is 15 or more, add 1.

I'd be reluctant to reject and re-sample as that can cause correlation plains to appear in linear congruential generators.

like image 44
Bathsheba Avatar answered Oct 04 '22 17:10

Bathsheba


Right now I'm using this and it works without causing browser issues with infinities loops, also tested in mobile devices (using Ionic/Cordova):

function getRandomIndex(usedIndexs, maxIndex) {
    var result = 0;
    var min = 0;
    var max = maxIndex - 1;
    var index = Math.floor(Math.random()*(max-min+1)+min);

    while(usedIndexs.indexOf(index) > -1) {
        if (index < max) {
            index++;
        } else {
          index = 0;
        }
    }

    return index;
}
like image 21
Juan Saravia Avatar answered Oct 04 '22 16:10

Juan Saravia