Skip to content

Instantly share code, notes, and snippets.

@didasy
Created February 12, 2015 16:46
Show Gist options
  • Save didasy/a1b83b28ea6f5eb5a39b to your computer and use it in GitHub Desktop.
Save didasy/a1b83b28ea6f5eb5a39b to your computer and use it in GitHub Desktop.
Golang Array Shuffler
/*
An array shuffler with good randomness
*/
package main
import (
"fmt"
"math/big"
"crypto/rand"
)
func main() {
arr := []int{1,2,3,4,5,6,7,8,9}
shuffle(arr)
fmt.Println("Shuffled: ", arr)
}
func shuffle(arr []int) error {
l := len(arr)
max := big.NewInt(int64(l - 1))
shuf := make([]int, len(arr))
copy(shuf, arr)
for range shuf {
r, err := rand.Int(rand.Reader, max)
if err != nil {
return err
}
rn := int(r.Int64())
n := shuf[rn]
shuf = append(shuf[:rn], shuf[rn+1:]...)
shuf = append(shuf, n)
}
copy(arr, shuf)
return nil
}
@filinvadim
Copy link

filinvadim commented May 22, 2017

Thx!
But it is memoryleaker.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment