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

How to avoid generating duplicate random numbers in Golang?

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2024-06-01 16:46:01
Original
481 people have browsed it

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)
    }
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Latest Issues
How to choose golang web mvc framework
From 1970-01-01 08:00:00
0
0
0
Is it necessary to use nginx when using golang?
From 1970-01-01 08:00:00
0
0
0
golang - vim plug-in to write go
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template