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));