Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating random integer in range that doesn't start at zero

How can I generate numbers between 7 to 10? So far all I've figured out is generating in a range from 0-10:

Math.floor(Math.random()*11)
like image 709
Winthan Aung Avatar asked Jul 15 '11 02:07

Winthan Aung


People also ask

How do you not get zeros in math randomly?

Math. random() can never generate 0 because it starts with a non-zero seed. Set the seed to zero, the function does not work, or throws an error. A random number generator always returns a value between 0 and 1, but never equal to one or the other.

How do you generate a random number from within a range?

Method 1: Using Math. random() function is used to return a floating-point pseudo-random number between range [0,1) , 0 (inclusive) and 1 (exclusive). This random number can then be scaled according to the desired range.

How do you generate a random number excluding 0 in Java?

int num = 10; Random rand = new Random(); int ran = rand. nextInt(num); if (ran==0){ ran= ran+1; } System. out. println("random : "+ran);


3 Answers

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

for(var x = 0; x < 5; x++) {
    console.log(getRandom(7, 10));
}
like image 92
Jordan Avatar answered Oct 04 '22 23:10

Jordan


Math.floor(7 + Math.random() * 4) will generate numbers from 7 to 10 inclusive.

like image 23
David Titarenco Avatar answered Oct 04 '22 23:10

David Titarenco


Just say this:

Math.floor(Math.random()*4) + 7

This will generate a random number from 0-3 and then add 7 to it, to get 7-10.

like image 4
Justin Ethier Avatar answered Oct 04 '22 23:10

Justin Ethier