7

I am looking to pick out random (that is pseudorandom) elements from a vector. The function would have an input, call it r, that would select the number of elements to be selected. Also, the vector, call it v, would also have to be an input. This is something I have never attempted and don't know where to begin in the process.

Assumptions going into the construction would be r is less than the number of elements in v. Duplicate elements selected from v would also not be an issue. To be clear the elements will be strictly numbers in fact they will be floating points, and I would like to retain that structure upon selection.

I have tried something along the lines of

(take 2 (iterate rand-nth [2 3 4 5 6 7]))

but return the vector and a random element from the list, i.e.

([2 3 4 5 6 7] 7)

Some similar posts from java include: How to choose a random element in this array only once across all declared objects in main?

Take n random elements from a List<E>?

3
  • (repeatedly n (rand-int (count v)))
    – Kevin
    Commented Mar 16, 2014 at 19:01
  • If you allow repeated elements, why does r have to be limited to the number of elements in v?
    – Thumbnail
    Commented Mar 16, 2014 at 19:11
  • It's a constraint that I wanted to impose. I'm looking for r in v and don't want |r| to exceed the length of v. It's an artificial constraint.
    – sunspots
    Commented Mar 16, 2014 at 19:13

3 Answers 3

13

You want repeatedly not iterate here

(repeatedly 2 #(rand-nth [2 3 4 5 6 7]))
4

A function to return r random elements from vector v in a vector is ...

(defn choose-random [r v]
  (mapv v (repeatedly r #(rand-int (count v)))))
1

If you want to have distinct vector elements in the return vector you could use :

(defn random-take-n [n v]
  (->> (shuffle v)
  (take n)))

(random-take-n 4 (range 200))
;; => (19 14 172 95)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.