Logo

Programming-Idioms

History of Idiom 15 > diff from v37 to v38

Edit summary for version 38 by programming-idioms.org:
Restored version 36

Version 37

2017-03-31, 14:42:17

Version 38

2017-03-31, 16:57:05

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.

Extra Keywords
choose
Extra Keywords
choose
Code
function pick(a, b) {
    return Math.floor(Math.random()*6);
}
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