haxtar
haxtar

Reputation: 2070

generating unique random numbers in Julia

This statement is often successful in generating 3 unique random numbers, but sometimes it only generates 2 unique numbers.

rand(1:length(matches), 3)

How can I rewrite this so I ensure 3 unique random numbers are always generated. (I am open to using other functions, etc, as well)

Thanks

Upvotes: 13

Views: 3266

Answers (3)

廖晓娅
廖晓娅

Reputation: 1

Well, it depends on the number of length(matches).

I suggest you can try these three methods to find one with minimum time cost:

    n = length(matches)
    using Random
    shuffle(1:n)[1:3]
    randperm(n)[1:3]

    using StatsBase
    sample(1:n, 3, replace=false)

Upvotes: 0

Michael Ohlrogge
Michael Ohlrogge

Reputation: 10980

Simple answer: (more full explanation below)

using StatsBase
MyRand = sample(1:10, 3, replace = false)   

There are a lot of complications that could go into this. For instance, whenever drawing random numbers, there is always some distribution that is drawn from. If you are drawing many random numbers, then the usual description of this in statistics is that you are drawing from a multi-dimensional distribution. If your distribution is discrete (i.e. any specific number has a positive probability of being selected) it will actually be a different distribution if you specify that no two entries can equal each other. Thus, depending on exactly what you want, this could get relatively complicated relatively quickly. E.g. if you want 5 Poisson random variables but with the stipulation that no two are equal to each other - to accomplish this in code is relatively straightforward, but the specifics of the distribution that would produce this are more involved and the variables you draw will no longer be standard Poisson random variables. Depending on your application, this might or might not be important for you to keep in mind.

BUT, in this case, it looks like you are just looking to select three random elements from a list of some sorts, assigning equal probability to each being selected, and ensuring that no element gets selected twice. In this case, the sample() function from StatsBase will do the trick, with the selection of the replace = false option (i.e. sampling "without replacement" meaning that you remove a number from the pool of possible results once it gets selected).

Upvotes: 10

Alexander Morley
Alexander Morley

Reputation: 4181

The sample function in StatsBase has a replace option.

e.g.

using StatsBase
sample(1:10, 3, replace=false)

Docs here: https://statsbasejl.readthedocs.io/en/latest/

Upvotes: 13

Related Questions