duanaigua4033 2018-05-10 13:39
浏览 89
已采纳

如何在golang中获取随机数样本? [关闭]

Or I have to use straightforward way like:

var arr []int

for i := 0; i < 5; i++ {
    arr = append(arr, rand.Intn(100))
}
  • 写回答

1条回答 默认 最新

  • douchan4674 2018-05-10 13:48
    关注

    What you did is clean and fast enough. What you could improve on it is to pre-allocate the slice and fill it using a for.. range loop like this:

    s := make([]int, 5)
    for i := range s {
        s[i] = rand.Intn(100)
    }
    

    The math/rand package also has a rand.Read() function which fills a slice with random bytes. So if you want to fill a []byte slice with random data, this is all it takes:

    s := make([]byte, 100)
    rand.Read(s) // This never returns an error
    

    Another interesting way would be to take advantage of rand.Rand being an io.Reader. Which means it has a Read() method which fills a []byte with random data.

    This combined with the encoding/binary package, you can "fill" variables with random data. Create and pass a rand.Rand to the binary.Read() function as the source, and that's it.

    This is how it would look like:

    r := rand.New(rand.NewSource(time.Now().UnixNano()))
    
    s := make([]int32, 5)
    err := binary.Read(r, binary.BigEndian, &s)
    if err != nil {
        panic(err)
    }
    fmt.Println(s)
    

    Output:

    [203443513 1611652563 -235795288 8294855 -802604260]
    

    This is "cool" enough to even fill structs for example:

    var point struct{ X, Y int16 }
    err = binary.Read(r, binary.BigEndian, &point)
    if err != nil {
        panic(err)
    }
    fmt.Printf("%+v", point)
    

    Output:

    {X:-15471 Y:2619}
    

    Try these examples on the Go Playground.

    One handicap of using binary.Read() is that–understandably–it can only fill values of fixed-size types, and the most famous exception is the common int type, whose size is not fixed (architecture dependent). So you can't fill an []int slice or a struct with a field of int type. That's why I used int32 and int16 types in the above examples.

    Of course in these solutions you could not limit the range of random numbers that are used to fill your variables. For that, the initial loop is still easier.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Android studio AVD启动不了
  • ¥15 陆空双模式无人机怎么做
  • ¥15 想咨询点问题,与算法转换,负荷预测,数字孪生有关
  • ¥15 C#中的编译平台的区别影响
  • ¥15 软件供应链安全是跟可靠性有关还是跟安全性有关?
  • ¥15 电脑蓝屏logfilessrtsrttrail问题
  • ¥20 关于wordpress建站遇到的问题!(语言-php)(相关搜索:云服务器)
  • ¥15 【求职】怎么找到一个周围人素质都很高不会欺负他人,并且未来月薪能够达到一万以上(技术岗)的工作?希望可以收到写有具体,可靠,已经实践过了的路径的回答?
  • ¥15 Java+vue部署版本反编译
  • ¥100 对反编译和ai熟悉的开发者。