Exclude certain numbers from a range of random numbers in JavaScript

Advertisements

I am trying to generate random numbers.
I do it like this:

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

I’m trying to get a number in the range from 0 to 100. Excluding the range from 40 to 60 from the answer
How to do it?

>Solution :

Calculate a random number that spans the length of the inclusive range, then readjust that to either be at the first min number or the second min number.

Note that this algorithm gives numbers on the interval [min1, max1) U [min2, max2), which is also min1 <= num < max1 OR min2 <= num < max2.

function getRandom(min1, max1, min2, max2) {
  const range = (max1 - min1) + (max2 - min2);
  const initial = range * Math.random();
  if (initial < max1 - min1) {
    return initial + min1;
  } else {
    return initial + min2 - (max1 - min1);
  }
}

console.log(getRandom(0, 40, 60, 100));

Leave a ReplyCancel reply