How to choose a random element from an array in Scala?

不问归期 提交于 2019-11-30 06:28:56

问题


For example, there is a Scala array val A = Array("please", "help", "me"). How to choose a random element from this array?


回答1:


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



回答2:


import scala.util.Random

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



回答3:


import scala.util.Random

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



回答4:


We can also add some safety with the Option monad (using the lift function, and a condition)

Actually, if you use this function on Arrays (that could be empty), your result will always be an Option.

Referencial Transparency FTW \o/

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



回答5:


A better answer that does not involve reshuffling the array at all would be this:

import scala.util.Random

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

This also works generically




回答6:


If you want a more idiomatic solution, consider using the typeclass pattern (implicit classes in 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)))
}

Now if the implicit class is in scope, you can:

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

If you are sure that the option contains some value, you can use the get method.

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

Nonetheless, pattern matching or getOrElse are recommended:

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. 

Note that the randomChoice method assumes substitution of elements.



来源:https://stackoverflow.com/questions/5051574/how-to-choose-a-random-element-from-an-array-in-scala

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!