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

huangapple go评论71阅读模式
英文:

Go: Get a set of unique random numbers

问题

如何获取一组不重复的随机数?

Go代码示例:

package main

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

func main() {
	rand.Seed(time.Now().UnixNano()) // 设置随机数种子

	set := make(map[int]bool) // 创建一个用于存储随机数的集合

	for len(set) < 10 { // 直到集合中的元素数量达到10个为止
		v := rand.Intn(100) // 生成一个0到99之间的随机数

		if !set[v] { // 如果集合中不存在该随机数
			set[v] = true // 将该随机数添加到集合中
			fmt.Println(v) // 打印该随机数
		}
	}
}

这段代码会生成一组不重复的随机数。它使用了一个map来存储已经生成的随机数,通过判断随机数是否已经存在于集合中来确保生成的随机数不重复。

英文:

How do I get a set of random numbers that are not repeated in the set?

Go:

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

This gives me, sometimes, two or three of the same numbers. I want all of them different. How do I do this?

答案1

得分: 20

例如,

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

英文:

For example,

package main

import (
	&quot;fmt&quot;
	&quot;math/rand&quot;
	&quot;time&quot;
)

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

Output:

87
75
89
74
17
32
56
44
36
0

Playground:

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

huangapple
  • 本文由 发表于 2014年8月30日 21:52:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/25583082.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定