function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min)) + min; } 
The getRandomInt function does not return the max value, how can this be implemented?

1 answer 1

The Math.random () method returns a value in the interval [0; 1) [0; 1) , that is, not including the upper limit.

When multiplied by (max - min) interval changes to the next [0; max-min) [0; max-min) , again not including the upper bound.

With a further shift to min we get the interval [min, max)

Consequently, for max enter the interval after the shift, the interval must end with max+1

So before the shift: max+1 - min

From here we get the factor max+1 - min instead of max - min

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