gpt4 book ai didi

Go:获取一组唯一的随机数

转载 作者:IT王子 更新时间:2023-10-29 01:23:22 26 4
gpt4 key购买 nike

如何得到一组在集合中不重复的随机数?

开始:

for i := 0; i < 10; i++ {
v := rand.Intn(100)
fmt.Println(v)
}

有时,这会给我两个或三个相同的数字。我希望他们都不同。我该怎么做?

最佳答案

例如,

package main

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

func main() {
rand.Seed(time.Now().UnixNano())
p := rand.Perm(100)
for _, r := range p[:10] {
fmt.Println(r)
}
}

输出:

87
75
89
74
17
32
56
44
36
0

Playground :

http://play.golang.org/p/KfdCW3zO5K

关于Go:获取一组唯一的随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25583082/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com