Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return multiple random elements from List scala

Tags:

scala

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 ?

like image 704
blue-sky Avatar asked Dec 01 '22 19:12

blue-sky


1 Answers

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.

like image 200
Apocalisp Avatar answered Dec 05 '22 06:12

Apocalisp