【发布时间】:2016-05-14 05:15:46
【问题描述】:
我正在尝试在 Go 中实现一个使用 crypto/rand 而不是 math/rand 的字符串 shuffle 函数。 Fisher-Yates Shuffle 需要随机整数,所以我尝试实现该功能,而不必使用依赖于math/big 的crypto/rand Int。以下是我迄今为止提出的最好的方法,但有更好的方法吗?我找不到现有示例这一事实让我想知道是否有充分的理由为什么没有人这样做!
package main
import "crypto/rand"
import "fmt"
import "encoding/binary"
func randomInt(max int) int {
var n uint16
binary.Read(rand.Reader, binary.LittleEndian, &n)
return int(n) % max
}
func shuffle(s *[]string) {
slice := *s
for i := range slice {
j := randomInt(i + 1)
slice[i], slice[j] = slice[j], slice[i]
}
*s = slice
}
func main() {
slice := []string{"a", "b", "c", "d", "e", "f", "h", "i", "j", "k"}
shuffle(&slice)
fmt.Println(slice)
}
【问题讨论】:
标签: go cryptography shuffle