-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsample.go
More file actions
55 lines (46 loc) · 1.14 KB
/
sample.go
File metadata and controls
55 lines (46 loc) · 1.14 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package enumerators
import (
"math/rand"
"sync"
"time"
)
var globalRand = rand.New(rand.NewSource(time.Now().UnixNano()))
var globalRandMu sync.Mutex
// Sample returns a random sample of n elements from the enumerator.
// If n <= 0, it returns an empty enumerator.
// If n >= length, it returns all elements in random order.
// The enumerator is consumed eagerly.
func Sample[T any](enumerator Enumerator[T], n int) Enumerator[T] {
slice, err := ToSlice(enumerator)
if err != nil {
return Generate(func() (T, bool, error) {
return *new(T), false, err
})
}
if n <= 0 {
return Empty[T]()
}
sampleRand := nextSampleRand()
if n >= len(slice) {
// Shuffle all
sampleRand.Shuffle(len(slice), func(i, j int) {
slice[i], slice[j] = slice[j], slice[i]
})
return Slice(slice)
}
// Reservoir sampling for n items.
result := make([]T, n)
copy(result, slice[:n])
for i := n; i < len(slice); i++ {
j := sampleRand.Intn(i + 1)
if j < n {
result[j] = slice[i]
}
}
return Slice(result)
}
func nextSampleRand() *rand.Rand {
globalRandMu.Lock()
defer globalRandMu.Unlock()
return rand.New(rand.NewSource(globalRand.Int63()))
}