Completed
Push — master ( a1ea93...617d0b )
by Hayrullah
14s queued 13s
created

shuffle.go   A

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 7
dl 0
loc 31
rs 10
c 0
b 0
f 0
1
package gotil
2
3
import (
4
	"math/rand"
5
	"time"
6
)
7
8
// Shuffle returns a new array of shuffled values, using a version of the Fisher-Yates shuffle.
9
// The default seed is time.Now().UnixNano()
10
// To change seed use gotil.ShuffleSeed()
11
// 	seed := int64(58239238)
12
//	Seed you will get the same sequence of pseudo­random numbers
13
// 	each time you run the program.
14
// 	data := []int64{-100, -5, 30, 100}
15
// 	newData := Shuffle(data)
16
// 	// Output: [-5 100 -100 30]
17
func Shuffle[T any](s []T) []T {
18
	return ShuffleSeed(s, time.Now().UnixNano())
19
}
20
21
// ShuffleSeed returns a new array of shuffled values, using a version of the Fisher-Yates shuffle with given seed
22
// To use randomize seed -> gotil.ShuffleSeed()
23
//
24
// seed := time.Now().UnixNano()
25
// Seed you will get the same sequence of pseudo­random numbers
26
// each time you run the program.
27
//
28
// 	data := []int64{-100, -5, 30, 100}
29
// 	newData := ShuffleSeed(data, seed)
30
// 	// Output: [-5 100 -100 30]
31
func ShuffleSeed[T any](s []T, seed int64) []T {
32
	rand.Seed(seed)
33
	newSlice := copySlice(s)
34
	for i := len(newSlice) - 1; i > 0; i-- { // Fisher–Yates shuffle
35
		j := rand.Intn(i + 1)
36
		newSlice[i], newSlice[j] = newSlice[j], newSlice[i]
37
	}
38
	return newSlice
39
}
40