vendredi 7 octobre 2016

How to generate *unique* random number in go using standard library

Question: How can I generate a stream of unique random number in go?

Namely, I want to guarantee there's no duplication in array a using math/rand and/or standard go library utilities.

func RandomNumberGenerator() *rand.Rand {
    s1 := rand.NewSource(time.Now().UnixNano())
    r1 := rand.New(s1)

    return r1
}
rng := RandomNumberGenerator()

N := 10000
for i := 0; i < N; i++ {
    a[i] = rng.Int()
}


There are questions and solutions on how to generate a series of random number in go, for example, here, and here.

But right now I want to generate a series of random number that does not duplicate with previous value. Is there a standard/recommended way to do it in go?

My guess is to (1)use permutation or to (2) keep track of previously generated numbers and regenerate a value if it's been generated before.

But solution (1) sounds like an overkill if I only want a few number and (2) sounds very time consuming if I end up generating a long series of random numbers due to collision, and I guess it's also very memory-consuming.




Aucun commentaire:

Enregistrer un commentaire