Go: Get a set of unique random numbers

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

Go:

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

      

This gives me, sometimes, two or three of the same number. I want them all to be different. How to do it?

+3


source to share


1 answer


For example,

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)
    }
}

      

Output:



87
75
89
74
17
32
56
44
36
0

      

Exposition:

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

+10


source







All Articles