Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go: Get a set of unique random numbers

Tags:

go

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?

like image 461
user3918985 Avatar asked Aug 30 '14 13:08

user3918985


1 Answers

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

like image 165
peterSO Avatar answered Nov 09 '22 19:11

peterSO