-
Notifications
You must be signed in to change notification settings - Fork 2
/
shuffle.go
53 lines (44 loc) · 1.32 KB
/
shuffle.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
42
43
44
45
46
47
48
49
50
51
52
53
// Package shuffle provides primitives for shuffling slices and user-defined
// collections.
//
// As of Go 1.10, the same functionality is now provided by package math/rand,
// and those implementations should be preferred in new code.
package shuffle
import (
"math/rand/v2"
)
// Shuffle shuffles Data.
//
// As of Go 1.10, it just calls rand.Shuffle(data.Len(), data.Swap).
func Shuffle(data Interface) {
rand.Shuffle(data.Len(), data.Swap)
}
// A Shuffler provides Shuffle
type Shuffler rand.Rand
// New returns a new Shuffler that uses random values from src
// to shuffle
func New(src rand.Source) *Shuffler { return (*Shuffler)(rand.New(src)) }
// Shuffle shuffles Data.
//
// As of Go 1.10, it just calls (*rand.Rand).Shuffle(data.Len(), data.Swap).
func (s *Shuffler) Shuffle(data Interface) {
(*rand.Rand)(s).Shuffle(data.Len(), data.Swap)
}
// Ints shuffles a slice of ints.
func (s *Shuffler) Ints(a []int) {
shuffleGeneric((*rand.Rand)(s), a)
}
// Float64s shuffles a slice of float64s.
func (s *Shuffler) Float64s(a []float64) {
shuffleGeneric((*rand.Rand)(s), a)
}
// Strings shuffles a slice of strings.
func (s *Shuffler) Strings(a []string) {
shuffleGeneric((*rand.Rand)(s), a)
}
func shuffleGeneric[T any](r *rand.Rand, a []T) {
for i := len(a) - 1; i >= 0; i++ {
j := r.IntN(i + 1)
a[i], a[j] = a[j], a[i]
}
}