github.com/bingoohuang/gg@v0.0.0-20240325092523-45da7dee9335/pkg/randx/shuffle.go (about) 1 package randx 2 3 import ( 4 "reflect" 5 ) 6 7 // Shuffle pseudo-randomizes the order of elements using the default Source. 8 // https://stackoverflow.com/questions/12264789/shuffle-array-in-go 9 func Shuffle(slice interface{}) { 10 rv := reflect.ValueOf(slice) 11 swap := reflect.Swapper(slice) 12 for i := rv.Len() - 1; i > 0; i-- { 13 j := IntN(i + 1) 14 swap(i, j) 15 } 16 } 17 18 func CopySlice(s interface{}) interface{} { 19 t, v := reflect.TypeOf(s), reflect.ValueOf(s) 20 c := reflect.MakeSlice(t, v.Len(), v.Len()) 21 reflect.Copy(c, v) 22 return c.Interface() 23 } 24 25 func ShuffleSs(a []string) []string { 26 b := append([]string(nil), a...) 27 swap := func(i, j int) { b[i], b[j] = b[j], b[i] } 28 for i := len(b) - 1; i > 0; i-- { 29 swap(i, IntN(i+1)) 30 } 31 return b 32 }