Created
February 12, 2015 16:46
-
-
Save didasy/a1b83b28ea6f5eb5a39b to your computer and use it in GitHub Desktop.
Golang Array Shuffler
This file contains 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
/* | |
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thx!
But it is memoryleaker.