Avi Flax
Avi Flax

Reputation: 51839

Is there a more idiomatic way to get N random elements of a collection in Clojure?

I’m currrently doing this: (repeatedly n #(rand-nth (seq coll))) but I suspect there might be a more idiomatic way, for 2 reasons:

I suppose I could figure out a way to use reduce but that seems like it would be tricky and less efficient, as it would have to process the entire collection, since reduce is not lazy.

Upvotes: 4

Views: 1048

Answers (2)

Daniel Neal
Daniel Neal

Reputation: 4173

I know it's not exactly what you're asking - but if you're doing a lot of sampling and statistical work, you might be interested in Incanter ([incanter "1.5.2"]). Incanter provides the function sample, which provides options for sample size, and replacement.

(require '[incanter.stats :refer [sample]]))

(sample [1 2 3 4 5 6 7] :size 5 :replacement false) 
; => (1 5 6 2 7)

Upvotes: 1

barracel
barracel

Reputation: 1829

An easy solution but not optimal for big collections could be:

(take n (shuffle coll))

Has the "advantage" of not repeating elements. Also you could implement a lazy-shuffle but it will involve more code.

Upvotes: 7

Related Questions