喵-见缝插针 2012-09-07 15:29 采纳率: 0%
浏览 191
已采纳

戈朗随机数发生器如何正确播种

I am trying to generate a random string in Go and here is the code I have written so far:

package main

import (
    "bytes"
    "fmt"
    "math/rand"
    "time"
)

func main() {
    fmt.Println(randomString(10))
}

func randomString(l int) string {
    var result bytes.Buffer
    var temp string
    for i := 0; i < l; {
        if string(randInt(65, 90)) != temp {
            temp = string(randInt(65, 90))
            result.WriteString(temp)
            i++
        }
    }
    return result.String()
}

func randInt(min int, max int) int {
    rand.Seed(time.Now().UTC().UnixNano())
    return min + rand.Intn(max-min)
}

My implementation is very slow. Seeding using time brings the same random number for a certain time, so the loop iterates again and again. How can I improve my code?

转载于:https://stackoverflow.com/questions/12321133/golang-random-number-generator-how-to-seed-properly

  • 写回答

4条回答 默认 最新

  • Lotus@ 2012-09-07 15:33
    关注

    Each time you set the same seed, you get the same sequence. So of course if you're setting the seed to the time in a fast loop, you'll probably call it with the same seed many times.

    In your case, as you're calling your randInt function until you have a different value, you're waiting for the time (as returned by Nano) to change.

    As for all pseudo-random libraries, you have to set the seed only once, for example when initializing your program unless you specifically need to reproduce a given sequence (which is usually only done for debugging and unit testing).

    After that you simply call Intn to get the next random integer.

    Move the rand.Seed(time.Now().UTC().UnixNano()) line from the randInt function to the start of the main and everything will be faster.

    Note also that I think you can simplify your string building:

    package main
    
    import (
        "fmt"
        "math/rand"
        "time"
    )
    
    func main() {
        rand.Seed(time.Now().UTC().UnixNano())
        fmt.Println(randomString(10))
    }
    
    func randomString(l int) string {
        bytes := make([]byte, l)
        for i := 0; i < l; i++ {
            bytes[i] = byte(randInt(65, 90))
        }
        return string(bytes)
    }
    
    func randInt(min int, max int) int {
        return min + rand.Intn(max-min)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集
  • ¥15 在启动roslaunch时出现如下问题