How to return multiple random items from scala list

How to return a few random items from a list.

This question How to select a random element from an array in Scala? refers to the use of:

import scala.util.Random
val A = Array("please", "help", "me")
Random.shuffle(A.toList).head

The mutable in me thinks that I can create a for loop and continue to select the next random element (except for the one already selected) and add it to the new list. Is there a more idiomatic / functional way to achieve this in Scala?

+4
source share
2 answers

The method headwill return the first element of the list, but take(n)will return to the nelements from the beginning of the list. So after you shuffled the list, just use take:

def takeRandomN[A](n: Int, as: List[A]) =
  scala.util.Random.shuffle(as).take(n)

as n as.

, , , , , , . Array , List .

+18

"" mutables/vars. :

def takeRandomFrom[T](n: Int, list: List[T]): List[T] = {
  @tailrec
  def innerTake(n:Int, list: List[T], result: List[T]): List[T] = {
    if (n == 0 || list.isEmpty) {
  result
} else {
  innerTake(n - 1, list.tail, list.head :: result)
}
  }

  innerTake(n, Random.shuffle(list), Nil)
}  

takeRandomFrom(2, Array("please", "help", "me").toList)
+1

All Articles