A random integer from min to max
Create a function
randomInteger(min, max) that generates a random integer number from
max including both
max as possible values.
Any number from the interval
min..max must appear with the same probability.
Examples of its work:
alert( random(1, 5) ); // 1 alert( random(1, 5) ); // 3 alert( random(1, 5) ); // 5
The simple but wrong solution
The simplest, but wrong solution would be to generate a value from
max and round it:
The function works, but it is incorrect. The probability to get edge values
max is two times less than any other.
If you run the example above many times, you would easily see that
2 appears the most often.
That happens because
Math.round() gets random numbers from the interval
1..3 and rounds them as follows:
values from 1 ... to 1.4999999999 become 1 values from 1.5 ... to 2.4999999999 become 2 values from 2.5 ... to 2.9999999999 become 3
Now we can clearly see that
1 gets twice less values than
2. And the same with
The correct solution
There are many correct solutions to the task. One of them is to adjust interval borders. To ensure the same intervals, we can generate values from
0.5 to 2.5, thus adding the required probabilities to the edges:
An alternative way could be to use
Math.floor for a random number from
Now all intervals are mapped this way:
values from 1 ... to 1.9999999999 become 1 values from 2 ... to 2.9999999999 become 2 values from 3 ... to 3.9999999999 become 3
All intervals have the same length, making the final distribution uniform.