DEV Community

Cover image for To the point - generating random numbers in golang
HM
HM

Posted on

To the point - generating random numbers in golang

Generating random numbers

(integers for the sake of this post)

Usually

Most commonly, you would use the math/rand and the time pkg to seed the rand generator in go. This is shown below:

// code#1 package main import ( "fmt" "math/rand" "time" ) func main() { rand.Seed(time.Now().UnixNano()) x := rand.Intn(5) // An int between [0,5) fmt.Println(x) } 
Enter fullscreen mode Exit fullscreen mode

Unusually

Most of times, code#1 will do the job, BUT what if your randomness cannot depend on time alone.

Problem

As an example, suppose you want to create a function that must return two random numbers between 0 and n

Thought 1

You could math/rand.Perm(n) seeded with time.Now().UnixNano() to obtain a slice of n integers. And then pick the first two. Something like:

//code#2 func main() { rand.Seed(time.Now().UnixNano()) x := rand.Perm(5) fmt.Println(x[0], x[1]) } 
Enter fullscreen mode Exit fullscreen mode

BUT, this is highly inefficient especially for large values of n.

Thought 2

Make use of the crypto/rand package to generate a truly random int.
Something like:

// code#3 package main import ( "fmt" "crypto/rand" "math/big" ) func main() { x, _ := rand.Int(rand.Reader, big.NewInt(5)) y, _ := rand.Int(rand.Reader, big.NewInt(5)) fmt.Println(x, y) } 
Enter fullscreen mode Exit fullscreen mode

That's all! Happy randomizing!

Top comments (0)