Logo

Programming-Idioms

History of Idiom 15 > diff from v26 to v27

Edit summary for version 27 by :
[Go] +DemoURL, +DocURL to rand.Intn

Version 26

2015-11-30, 12:37:26

Version 27

2015-12-30, 17:10:40

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.

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.
Doc URL
https://golang.org/pkg/math/rand/#Intn
Demo URL
http://play.golang.org/p/Tk1Gl2sxv-