Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random integer in a certain range excluding one number

I would like get a random number in a range excluding one number (e.g. from 1 to 1000 exclude 577). I searched for a solution, but never solved my issue.

I want something like:

Math.floor((Math.random() * 1000) + 1).exclude(577);

I would like to avoid for loops creating an array as much as possible, because the length is always different (sometimes 1 to 10000, sometimes 685 to 888555444, etc), and the process of generating it could take too much time.

I already tried:

  • Javascript - Generating Random numbers in a Range, excluding certain numbers

  • How can I generate a random number within a range but exclude some?

How could I achieve this?

like image 637
P. Frank Avatar asked Dec 09 '15 15:12

P. Frank


People also ask

How do you exclude a number in math randomly?

math. random when specified with two values returns a number in the range [m, n]. -1 < 0 < 1 therefore 0 is a valid number in this range. You can't exclude a number, so your best bet would be to do randomise again until the result is not 0.

How do you get a random integer in a range?

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.

How do you exclude numbers in a range in Python?

If you want to exclude 0 then change your range to (1,11). The way range works is the lower limit is inclusive where as upper limit is exclusive. On an unrelated note, if your lower limit is 0, you need not include the lower limit and write it as range(11) which is same as range(0,11).


2 Answers

The fastest way to obtain a random integer number in a certain range [a, b], excluding one value c, is to generate it between a and b-1, and then increment it by one if it's higher than or equal to c.

Here's a working function:

function randomExcluded(min, max, excluded) {
    var n = Math.floor(Math.random() * (max-min) + min);
    if (n >= excluded) n++;
    return n;
}

This solution only has a complexity of O(1).

like image 100
Marco Bonelli Avatar answered Oct 23 '22 12:10

Marco Bonelli


One possibility is not to add 1, and if that number comes out, you assign the last possible value.

For example:

var result = Math.floor((Math.random() * 100000));
if(result==577) result = 100000;

In this way, you will not need to re-launch the random method, but is repeated. And meets the objective of being a random.

like image 28
Jesus Cuesta Avatar answered Oct 23 '22 12:10

Jesus Cuesta