Problem
Is it possible to produce a random integer inside a given range using JavaScript?
For instance, suppose you have a range of 1 to 6, and the random number may be 1, 2, 3, 4, 5, or 6.
Asked by Mirgorod
Solution #1
It does something “additional” by allowing random intervals that do not begin with 1. So, for example, you could get a random number between 10 and 15. Flexibility.
Answered by Francisc
Solution #2
If you needed a random integer between 1 (and only 1) and 6, you’d use the following formula:
Where:
Answered by khr055
Solution #3
Between min (included) and max (included), returns an integer random number:
function randomInteger(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
Alternatively, any number between min (included) and max (excluded):
function randomNumber(min, max) {
return Math.random() * (max - min) + min;
}
Useful examples (integers):
// 0 -> 10
Math.floor(Math.random() * 11);
// 1 -> 10
Math.floor(Math.random() * 10) + 1;
// 5 -> 20
Math.floor(Math.random() * 16) + 5;
// -10 -> (-2)
Math.floor(Math.random() * 9) - 10;
** And, as Mozilla reminds us, it’s always good to be reminded:
Answered by Lior Elrom
Solution #4
Other solutions:
Try online
Answered by Vishal
Solution #5
TL;DR
function generateRandomInteger(min, max) {
return Math.floor(min + Math.random()*(max + 1 - min))
}
generateRandomInteger(-20, 20); to get a random number
EXPLANATION BELOW
We need a random integer between min and max, say X.
Right?
i.e. minimum = X maximum
When we take min out of the equation, the result is
(X – min) 0 0 0 0 0 0 0 0 0 0 0 0 0 0 (max – min)
Let’s multiply this by r, which is a random number.
r= (max – min) * r= (max – min) * r= (max – min) * r= (max – min) * r= (max – min) * r= (max – min)
Let’s now reintroduce min into the equation.
min = min + (X – min) * r = min + (max – min) * r r r r r r r r r r r r r r r r r r r r r
Now let’s choose a function that returns r and fits into our equation range of [min,max]. Only if 0=r=1 is this possible.
OK. Now, the range of r, i.e. [0,1], is quite similar to the output of the Math.random() function. Isn’t that so?
For example,
min + (max-min) * 0 = min
max = min + 1 * (max-min)
X = min + r * (max-min), where X has a range of min=X max.
The above result X is a random numeric. However due to Math.random() our left bound is inclusive, and the right bound is exclusive. To include our right bound we increase the right bound by 1 and floor the result.
function generateRandomInteger(min, max) {
return Math.floor(min + Math.random()*(max + 1 - min))
}
generateRandomInteger(-20, 20);
Answered by Faiz Mohamed Haneef
Post is based on https://stackoverflow.com/questions/4959975/generate-random-number-between-two-numbers-in-javascript