Skip to content

Instantly share code, notes, and snippets.

@roscopecoltran
Forked from quux00/knuth.go
Created May 8, 2018 07:18
Show Gist options
  • Save roscopecoltran/2aa4890a4853c13bdbeff5d2de376885 to your computer and use it in GitHub Desktop.
Save roscopecoltran/2aa4890a4853c13bdbeff5d2de376885 to your computer and use it in GitHub Desktop.
Knuth Fisher-Yates shuffle for Go (golang)
// implements Knuth or Fisher-Yates shuffle
package knuth
import (
"math/rand"
"time"
)
func init() {
rand.Seed(time.Now().UTC().UnixNano())
}
func Shuffle(slc []interface{}) {
N := len(slc)
for i := 0; i < N; i++ {
// choose index uniformly in [i, N-1]
r := i + rand.Intn(N-i)
slc[r], slc[i] = slc[i], slc[r]
}
}
func ShuffleInts(slc []int) {
N := len(slc)
for i := 0; i < N; i++ {
// choose index uniformly in [i, N-1]
r := i + rand.Intn(N-i)
slc[r], slc[i] = slc[i], slc[r]
}
}
func ShuffleStrings(slc []string) {
N := len(slc)
for i := 0; i < N; i++ {
// choose index uniformly in [i, N-1]
r := i + rand.Intn(N-i)
slc[r], slc[i] = slc[i], slc[r]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment