How to properly seed random number generator

前端 未结 9 1213
陌清茗
陌清茗 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 20:53

    If your aim is just to generate a sting of random number then I think it's unnecessary to complicate it with multiple function calls or resetting seed every time.

    The most important step is to call seed function just once before actually running rand.Init(x). Seed uses the provided seed value to initialize the default Source to a deterministic state. So, It would be suggested to call it once before the actual function call to pseudo-random number generator.

    Here is a sample code creating a string of random numbers

    package main 
    import (
        "fmt"
        "math/rand"
        "time"
    )
    
    
    
    func main(){
        rand.Seed(time.Now().UnixNano())
    
        var s string
        for i:=0;i<10;i++{
        s+=fmt.Sprintf("%d ",rand.Intn(7))
        }
        fmt.Printf(s)
    }
    

    The reason I used Sprintf is because it allows simple string formatting.

    Also, In rand.Intn(7) Intn returns, as an int, a non-negative pseudo-random number in [0,7).

提交回复
热议问题