How to properly seed random number generator

前端 未结 9 1235
陌清茗
陌清茗 2020-11-28 20:25

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\"
         


        
9条回答
  •  心在旅途
    2020-11-28 21:05

    I tried the program below and saw different string each time

    package main
    
    import (
        "fmt"
        "math/rand"
        "time"
    )
    
    func RandomString(count int){
      rand.Seed(time.Now().UTC().UnixNano()) 
      for(count > 0 ){
        x := Random(65,91)
        fmt.Printf("%c",x)
        count--;
      }
    }
    
    func Random(min, max int) (int){
     return min+rand.Intn(max-min) 
    }
    
    func main() {
     RandomString(12)
    }
    

    And the output on my console is

    D:\james\work\gox>go run rand.go
    JFBYKAPEBCRC
    D:\james\work\gox>go run rand.go
    VDUEBIIDFQIB
    D:\james\work\gox>go run rand.go
    VJYDQPVGRPXM
    

提交回复
热议问题