Generating Random Numbers in Golang

Random numbers are an essential part of many applications. Whether you’re building a game, running simulations, or need to generate unique IDs, you’ll likely need to generate random numbers at some point.

In Golang, the math/rand package provides functions for generating random numbers. Here’s a quick guide on how to use this package to generate random numbers.

Setting the Seed

Before generating random numbers, you need to set the seed value. The seed value is used as the starting point for generating random numbers. If you set the same seed value, you’ll get the same sequence of random numbers every time you run your program. To set the seed, use the rand.Seed() function:

import "math/rand"
import "time"

func main() {
    rand.Seed(time.Now().UnixNano())
    // generate random numbers here
}

In the example above, we’re setting the seed to the current Unix timestamp in nanoseconds. This ensures that the seed value is different every time the program runs.

Generating Integers

To generate a random integer, use the rand.Intn() function. This function takes a single argument, which is the maximum value for the random number (exclusive).

import "math/rand"

func main() {
    rand.Seed(time.Now().UnixNano())

    // generate a random integer between 0 and 9
    randomInt := rand.Intn(10)
}

In the example above, we’re generating a random integer between 0 and 9 (inclusive of 0 and exclusive of 10).

Generating Floats

To generate a random float, use the rand.Float64() function. This function returns a random float between 0.0 and 1.0 (exclusive of 1.0).

import "math/rand"

func main() {
    rand.Seed(time.Now().UnixNano())

    // generate a random float between 0.0 and 1.0
    randomFloat := rand.Float64()
}

In the example above, we’re generating a random float between 0.0 and 1.0 (exclusive of 1.0).

Generating Unique IDs

One common use case for random numbers is generating unique IDs. To generate a unique ID, you can use a combination of random integers and the strconv package to convert the integers to strings:

import "math/rand"
import "strconv"

func main() {
    rand.Seed(time.Now().UnixNano())

    // generate a random 8-digit ID
    id := ""
    for i := 0; i < 8; i++ {
        id += strconv.Itoa(rand.Intn(10))
    }
}

In the example above, we’re generating a random 8-digit ID by concatenating 8 random integers between 0 and 9.

Random number in golang

Example

The golang program below generates a number between 0 and 10. The starting number (0) is not given and thus 0 is assumed as lowest number.

package main

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

func random(min int, max int) int {
    return rand.Intn(max-min) + min
}

func main() {
    rand.Seed(time.Now().UnixNano())
    randomNum := random(0, 10)
    fmt.Printf("Random number: %d\n", randomNum)
}

To generate a number between 20 and 40 you can use the code below:


rand.Intn(max-min) + min

Generating Random Integers in a Range

In this program, we will generate random integers within a range using the math/rand package in Golang. The rand.Intn() function generates random integers in the range [0, n), where n is the argument passed to the function. To generate random integers within a specific range, we can simply shift the range using addition.

package main

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

func main() {
    rand.Seed(time.Now().UnixNano())
    
    // generate random integer between 10 and 20
    randInt := rand.Intn(11) + 10
    
    fmt.Println("Random integer between 10 and 20:", randInt)
}

In the code above, we generate a random integer between 10 and 20 by first generating a random integer between 0 and 10 using rand.Intn(11), and then adding 10 to shift the range.

Generating Random Floats

In this program, we will generate random floats between 0.0 and 1.0 using the math/rand package in Golang. The rand.Float64() function generates a random float between 0.0 and 1.0 (exclusive of 1.0).

package main

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

func main() {
    rand.Seed(time.Now().UnixNano())

    // generate random float between 0.0 and 1.0
    randFloat := rand.Float64()

    fmt.Println("Random float between 0.0 and 1.0:", randFloat)
}

In the code above, we generate a random float between 0.0 and 1.0 using rand.Float64().

Generating Unique IDs

In this program, we will generate a unique ID using a combination of random integers and the strconv package in Golang. We will generate a random 8-digit ID by concatenating 8 random integers between 0 and 9.

package main

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

func main() {
    rand.Seed(time.Now().UnixNano())

    // generate random 8-digit ID
    id := ""
    for i := 0; i < 8; i++ {
        id += strconv.Itoa(rand.Intn(10))
    }

    fmt.Println("Random 8-digit ID:", id)
}

In the code above, we generate a random 8-digit ID by concatenating 8 random integers between 0 and 9 using a for loop and the strconv.Itoa() function to convert the integers to strings. This can be useful for generating unique IDs for user accounts or other entities in a database.

Exercises

  1. Make a program that rolls a dice (1 to 6)
  2. Can you generate negative numbers?