Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Exclude certain numbers from a range of random numbers in JavaScript

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading