How can I return multiple random elements from a List .
This question How to choose a random element from an array in Scala? refers to using :
import scala.util.Random
val A = Array("please", "help", "me")
Random.shuffle(A.toList).head
The mutable in me is thinking I could create a for loop and keep selecting the next random element (excluding the one already selected) and add that to a new List. Is there a more idiomatic/functional way to achieve this in Scala ?
The head
method will return the first element of the list, but take(n)
will return up to n
elements from the front of the list. So after you shuffle the list, just use take
:
def takeRandomN[A](n: Int, as: List[A]) =
scala.util.Random.shuffle(as).take(n)
If your list as
is shorter than n
then this will simply shuffle as
.
It might seem like this is going to be slow for large lists that you only want a small subset from, but a random subset will be likely be uniformly sampled from the list, so you'll have to traverse the whole thing anyway. For an Array
or other structure with random access, you can do better, but for List
you cannot.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With