如何从Scala中的数组中选择一个随机元素?

时间:2011-02-19 15:14:08

标签: scala scala-2.8

例如,有一个Scala数组val A = Array("please", "help", "me")。如何从这个数组中选择一个随机元素?

6 个答案:

答案 0 :(得分:92)

import scala.util.Random

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

答案 1 :(得分:36)

import scala.util.Random

val A = List(1, 2, 3, 4, 5, 6)
A(Random.nextInt(A.size))

答案 2 :(得分:34)

import java.util.Random
// ...
val rand = new Random(System.currentTimeMillis())
val random_index = rand.nextInt(A.length)
val result = A(random_index)

答案 3 :(得分:1)

如果你想要一个更惯用的解决方案,可以考虑使用类型类模式(scala中的隐式类)。

implicit class ListOps[A](list: List[A]) {
  def getRandomElement: Option[A] = list match {
    case Nil => None
    case _ => list.lift(scala.util.Random.nextInt(list.size))
  }
  def randomChoice(n: Int): Option[List[A]] =
    (1 to n).toList.foldLeft(Option(List[A]()))((acc, e) => getRandomElement.flatMap(r => acc.map(a => a :+ r)))
}

现在,如果隐式类在范围内,您可以:

val randomElement: Option[String] = List("this", "is", "a", "list").getRandomElement

如果您确定该选项包含某个值,则可以使用get方法。

randomElement.get // This will return a String (or a NotSuchElementExeption)

尽管如此,建议使用模式匹配或getOrElse

randomElement match {
  case None => ??? // This is what you do when a None is encounter (e.g. for empty lists)
  case Some(result) => ??? // The variable result contains a string. 

注意 randomChoice方法假定替换元素。

答案 4 :(得分:0)

一个更好的答案,根本不涉及改组数组:

import scala.util.Random

object sample {
  //gets random element from array
  def arr[T](items:Array[T]):T = {
    items(Random.nextInt(items.length))
  }
}

这也是一般的工作

答案 5 :(得分:0)

我们还可以使用Option monad添加一些安全性(使用lift函数和条件)

实际上,如果你在Arrays上使用这个函数(可能是空的),你的结果将永远是一个选项。

参考透明度FTW \ o /

def getRandElemO[T](arr: Array[T]): Option[T] =
  if (arr.isEmpty) None
  else arr lift util.Random.nextInt(arr.length)
相关问题