Sampling without replacement


rand(1:20, 3)

gives three random integers in [1:20] with replacement. I see there are some threads on github on this issue, but I am not sure what is the recommended way with Julia 0.5 to sample without replacement.


See the StatsBase package:


Without using external packages you can use randperm and take the first three elements:


But this may not be very efficient, as it needs to create first an array of 20 elements.


You can use splice! to pick random elements and remove them from the collection:

function sample_wo_repl!(A,n)
    sample = Array{eltype(A)}(n)
    for i in 1:n
        sample[i] = splice!(A, rand(eachindex(A)))
    return sample


There is also randsubseq in Base. This efficiently samples an array without replacement, but with a given probability (per element) rather than a given number of elements. e.g. randsubseq(1:20, 0.15) produces 3 elements on average.