Logo

Programming-Idioms

History of Idiom 15 > diff from v24 to v25

Edit summary for version 25 by :

Version 24

2015-09-05, 15:23:16

Version 25

2015-10-29, 14:05:12

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
( + a (rand-int (- b a)))
Code
( + a (rand-int (- b a)))
Doc URL
http://clojuredocs.org/clojure.core/rand-int
Doc URL
http://clojuredocs.org/clojure.core/rand-int
Imports
import System.Random
Imports
import System.Random
Code
let pick (a, b) = randomRIO (a, b) :: IO Integer
 in pick (1, 6) >>= print

Code
let pick (a, b) = randomRIO (a, b) :: IO Integer
 in pick (1, 6) >>= print

Doc URL
http://hackage.haskell.org/package/random/docs/System-Random.html
Doc URL
http://hackage.haskell.org/package/random/docs/System-Random.html
Code
rand($a, $b)
Code
rand($a, $b)
Doc URL
http://php.net/manual/en/function.rand.php
Doc URL
http://php.net/manual/en/function.rand.php
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
Imports
import "math/rand"
Imports
import "math/rand"
Code
func pick(a,b int) int {
	return a + rand.Intn(b-a+1)
}
Code
func pick(a,b int) int {
	return a + rand.Intn(b-a+1)
}
Comments bubble
(b-a+1) is needed to have upper bound b included.
Comments bubble
(b-a+1) is needed to have upper bound b included.
Imports
#include <stdlib.h>
Imports
#include <stdlib.h>
Code
int pick(int a, int b)
{
	return a + rand() % (b - a);
}
Code
int pick(int a, int b)
{
	return a + rand() % (b - a);
}
Imports
import java.util.Random;
Imports
import java.util.Random;
Code
int pick(int a, int b){
	return a + new Random().nextInt(b - a + 1);
}
Code
int pick(int a, int b){
	return a + new Random().nextInt(b - a + 1);
}
Comments bubble
For performance, consider reusing the Random object.

(b-a+1) is needed to have upper bound b included.
Comments bubble
For performance, consider reusing the Random object.

(b-a+1) is needed to have upper bound b included.