-
Notifications
You must be signed in to change notification settings - Fork 0
/
shuffle.go
39 lines (36 loc) · 1.18 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
package gotil
import (
"math/rand"
"time"
)
// Shuffle returns a new array of shuffled values, using a version of the Fisher-Yates shuffle.
// The default seed is time.Now().UnixNano()
// To change seed use gotil.ShuffleSeed()
// seed := int64(58239238)
// Seed you will get the same sequence of pseudorandom numbers
// each time you run the program.
// data := []int64{-100, -5, 30, 100}
// newData := Shuffle(data)
// // Output: [-5 100 -100 30]
func Shuffle[T any](s []T) []T {
return ShuffleSeed(s, time.Now().UnixNano())
}
// ShuffleSeed returns a new array of shuffled values, using a version of the Fisher-Yates shuffle with given seed
// To use randomize seed -> gotil.ShuffleSeed()
//
// seed := time.Now().UnixNano()
// Seed you will get the same sequence of pseudorandom numbers
// each time you run the program.
//
// data := []int64{-100, -5, 30, 100}
// newData := ShuffleSeed(data, seed)
// // Output: [-5 100 -100 30]
func ShuffleSeed[T any](s []T, seed int64) []T {
rand.Seed(seed)
newSlice := copySlice(s)
for i := len(newSlice) - 1; i > 0; i-- { // Fisher–Yates shuffle
j := rand.Intn(i + 1)
newSlice[i], newSlice[j] = newSlice[j], newSlice[i]
}
return newSlice
}