Home  >  Article  >  Backend Development  >  How to avoid generating duplicate random numbers in Golang?

How to avoid generating duplicate random numbers in Golang?

WBOY
WBOYOriginal
2024-06-01 16:46:01416browse

Method to avoid generating repeated random numbers in Golang: Create a new random number generator rand.New(rand.Source). Use rand.NewSource(time.Now().UnixNano()) as the entropy source. Use rand.Intn(n) to generate random integers.

如何避免在 Golang 中生成重复的随机数?

#How to avoid generating repeated random numbers in Golang?

In Golang, generating random numbers requires using the math/rand package. Use the rand.Intn(n) function to generate a random integer in the range [0, n-1], where n is a positive integer. However, rand.Intn(n) may generate repeated random numbers in a concurrent environment.

To solve this problem, you can use the rand.New(rand.Source) function to create a new random number generator and use io.Reader as entropy source. In most cases, using rand.NewSource(time.Now().UnixNano()) as the entropy source will suffice.

The following is a sample code that shows how to use rand.NewSource to avoid generating duplicate random numbers:

package main

import (
    "math/rand"
    "time"
)

func main() {
    // 创建一个新的随机数生成器,并使用时间戳作为熵源
    r := rand.New(rand.NewSource(time.Now().UnixNano()))

    // 生成 10 个随机整数
    for i := 0; i < 10; i++ {
        result := r.Intn(100)
        println(result)
    }
}

By using rand.NewSource and time.Now().UnixNano() serve as a source of entropy to generate unique and unpredictable random numbers.

The above is the detailed content of How to avoid generating duplicate random numbers in Golang?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn