Logo

Programming-Idioms

History of Idiom 11 > diff from v41 to v42

Edit summary for version 42 by programming-idioms.org:
[Go] Fixed code and demo: list -> x

Version 41

2016-04-20, 20:23:02

Version 42

2016-04-20, 20:24:53

Idiom #11 Pick a random element from a list

List x must be non-empty.

Idiom #11 Pick a random element from a list

List x must be non-empty.

Imports
import "math/rand"
Imports
import "math/rand"
Code
func pickT(x []T) T {
	return x[rand.Intn(len(list))]
}
Code
func pickT(x []T) T {
	return x[rand.Intn(len(x))]
}
Comments bubble
If you decide to implement pickT, you will have to write it separately for each desired type T.
Comments bubble
If you decide to implement pickT, you will have to write it separately for each desired type T.
Doc URL
https://golang.org/pkg/math/rand/#Intn
Doc URL
https://golang.org/pkg/math/rand/#Intn
Demo URL
http://play.golang.org/p/RFt6HM-GQx
Demo URL
http://play.golang.org/p/u6Db7wb7v_