Logo

Programming-Idioms

History of Idiom 15 > diff from v22 to v23

Edit summary for version 23 by :

Version 22

2015-09-03, 13:49:52

Version 23

2015-09-03, 13:50:02

Idiom #15 Pick uniformly a random integer in [a..b]

Pick a random integer greater than or equals to a, inferior or equals to b. Precondition : a < b.

Idiom #15 Pick uniformly a random integer in [a..b]

Pick a random integer greater than or equals to a, inferior or equals to b. Precondition : a < b.

Code
function pick(a, b) {
    return a + Math.floor(Math.random() * (b- a+ 1));
}
Code
function pick(a, b) {
    return a + Math.floor(Math.random() * (b - a + 1));
}
Comments bubble
You have to build it from a floating-point random number. It is important to use floor , not round .
Comments bubble
You have to build it from a floating-point random number. It is important to use floor , not round .
Origin
http://stackoverflow.com/a/10134261/871134
Origin
http://stackoverflow.com/a/10134261/871134