Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Picking "Random" elements from a vector

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

like image 219
sunspots Avatar asked Mar 16 '14 18:03

sunspots


People also ask

How do you generate a random value from a vector in C++?

To generate the random values between 0 and n-1 , we can use the cstdlib's functions rand() and srand() or use any of the standard generators defined in the <random> header introduced in C++11.

How do you select a random element in C++?

rand() function in C++ The rand() function is an inbuilt function of C/C++ library. It helps to produce random numbers in a range in range between 0 and RAND_MAX. The seed used for this function's algorithm is initialized by a distinctive value of srand().


1 Answers

You want repeatedly not iterate here

(repeatedly 2 #(rand-nth [2 3 4 5 6 7]))
like image 172
A. Webb Avatar answered Dec 07 '22 19:12

A. Webb