-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchoices.go
41 lines (33 loc) · 905 Bytes
/
choices.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package sampler
// Choice returns a random item from items.
// If items is empty, Choice panics.
func Choice[E any](rnd Rand, items []E) E {
if len(items) == 0 {
panic("sample.Choice called with empty items")
}
return items[rnd.IntN(len(items))]
}
// Choices returns a random selection of n items from items.
// Items are not guaranteed to be unique.
func Choices[E any](rnd Rand, items []E, n int) []E {
return ChoicesAppend(rnd, nil, items, n)
}
// ChoicesAppend returns a random selection of n items from items.
// Items are appended to dst, which is grown if necessary.
// Items are not guaranteed to be unique.
func ChoicesAppend[E any](rnd Rand, dst, items []E, n int) []E {
if n == 0 {
return dst
}
if n < 0 {
n = len(items)
}
if dst == nil {
dst = make([]E, 0, n)
}
for i := 0; i < n; i++ {
idx := rnd.IntN(len(items))
dst = append(dst, items[idx])
}
return dst
}