9

I want to generate n unique elements from a list of numbers. I came across this answer but that only gives me one element. I want n distinct elements from the list.

How do I go about doing this?

I have tried using rand(list,n) but this sometimes gives me repeated elements from list so that doesn't work.

newtothis
  • 495
  • 3
  • 10

1 Answers1

13

Try Distributions.sample StatsBase.sample:

jl> using StatsBase: sample

jl> x = rand(10);

jl> sample(x, 3; replace=false)
3-element Vector{Float64}:
 0.6816165016249632
 0.8500982926818003
 0.6518188633423712
DNF
  • 11,584
  • 1
  • 26
  • 40
  • 1
    It looks like Distributions is just [reexporting sample from StatsBase](https://github.com/JuliaStats/Distributions.jl/blob/fb9ce8a1a3a3c860128c62bba8336140fe7dbef8/src/Distributions.jl#L262), but is there some benefit to using it via `Distributions` instead of directly using `StatsBase`? – Sundar R Oct 19 '21 at 12:28
  • I don't think so. I just cast about to see where `sample` was located, didn't find it in Statistics, so thought of Distributions.jl. I though Statistics depended on StasBase, so it never occurred to me to look there. – DNF Oct 19 '21 at 13:11