Domanda

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>?

È stato utile?

Soluzione

You want repeatedly not iterate here

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

Altri suggerimenti

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)))))

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

(defn random-take-n [n v]
  (let [indices (->> (range (count v))
                     (shuffle)
                     (take n))]
    (mapv v indexes)))
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top