10

How do I get a set of random numbers that are not repeated in the 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 numbers. I want all of them different. How do I do this?

user3918985
  • 4,278
  • 9
  • 42
  • 63

1 Answers1

20

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

Playground:

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

peterSO
  • 158,998
  • 31
  • 281
  • 276
  • Great. I thought my answer was false. Apparently not. – VonC Aug 30 '14 at 14:10
  • Becuase... you mention the same Seed function than I do? (also mentioned in http://stackoverflow.com/a/8288765/6309) – VonC Aug 30 '14 at 14:16
  • 1
    @VonC: Note my use of the `rand.Perm` function. Inserting the `rand.Seed` function before `rand.Intn` function, as you suggested, won't work. – peterSO Aug 30 '14 at 14:19