duanmiaosi0150 2014-09-21 16:37
浏览 286
已采纳

为什么每次重新启动程序时math / rand都返回相同的结果?

I'm a little confused. I have a random string generator, here's the code:

package utils

import (
  "fmt"
  "math/rand"
)

var chars = []rune("abcdefghijklmnopqrstuvwxyz0123456789")

func RandSeq(n int) string {
  b := make([]rune, n)
  for i := range b {
    b[i] = chars[rand.Intn(len(chars))]
  }
  fmt.Println(string(b))
  return string(b)
}

Every time I run this, it will generate a new random string, but if I restart the server the results will repeat themselves. Here are some results:

go run main.go
fpllngzieyoh43e0133ols6k1hh2gdny
xxvi7hvszwk1b182tvjzjpezi4hx9gvm
kir0xcta0opsb5qipjzb3h3x9kcegta5
m1zcv5drxckn42gb50anxndsckjdwgfw
5japz01zicapy9eqixuc9uehq235v48c
51wgg1gypq4s9miwn1dxkjqd614m58f0
fyy29g6ujmxbouxshy2plmkmhlnmdbfh
f7kq8u26873eql4yyp7fyilbb72nrtlc

go run main.go
fpllngzieyoh43e0133ols6k1hh2gdny
xxvi7hvszwk1b182tvjzjpezi4hx9gvm
kir0xcta0opsb5qipjzb3h3x9kcegta5
m1zcv5drxckn42gb50anxndsckjdwgfw
5japz01zicapy9eqixuc9uehq235v48c

Any idea why this is happening?

  • 写回答

2条回答 默认 最新

  • dongwen4487 2014-09-21 16:39
    关注

    You need to Seed the random number generator prior to generating any random numbers. A good value to use is the current unix timestamp:

    import (
        "math/rand"
        "time"
    )
    
    func main() {
        rand.Seed(time.Now().UnixNano())
    }
    

    Note that you should only seed the RNG once at startup (or after forking), not before each random number generation.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器