I wanted some information about generating random integers. I look for it in Google and Stack Overflow and mostly found code like this (in case we want numbers from 1 to 52):
var randInt=function(){
number=Math.floor(Math.random()*52+1);
};
and
var randNumMin = 1;
var randNumMax = 52;
var randInt = function (){
number = (Math.floor(Math.random() * (randNumMax - randNumMin + 1)) + randNumMin);
};
I read some references about Math.random and found that it is generating numbers from 0 to 1. In case Math.random generates 1, we will get number 5, so it means we will get error. I agree that it is very rare case, but it is possible. I slightly modified code to avoid that error (in our case generation of number 53). Here I think is a right code for generation random numbers in JavaScript. In your examples it generates only integers but I think it is possible to modify code and generate any kind of number:
var randInt = function(){
number = Math.floor(Math.random()*52+1);
if (number === 53){
randInt();
}
};
and
var randNumMin = 1;
var randNumMax = 52;
var randInt = function (){
number = (Math.floor(Math.random() * (randNumMax - randNumMin + 1)) + randNumMin);
if (number===53){
randInt();
}
};
The
Math.random()function generates random numbersxwhere0 <= x < 1. So it will never generate exactly 1, although it might come really close.From the documentation for
random: