Last active
February 13, 2019 10:33
-
-
Save quux00/8258425 to your computer and use it in GitHub Desktop.
Knuth Fisher-Yates shuffle for Go (golang)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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
rand.Seed
should not be called in the package.If it has to be done, it must be done just once per program in the
main
package. Because if every package that usesrand
callsSeed
, it may be called many times, while once is enough.