score:38
import java.util.Random
// ...
val rand = new Random(System.currentTimeMillis())
val random_index = rand.nextInt(A.length)
val result = A(random_index)
score:1
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
score:1
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.
score:4
We can also add some safety with the Option
monad (using the lift
method)
Actually, when using this method on any collection, even if your collection is empty, or your random index is out of boundaries, your result will always be an Option.
Drive safe <3
def getRandElemO[T](arr: Array[T]): Option[T] =
if (arr.isEmpty) None
else arr.lift(util.Random.nextInt(arr.length))
// or the one liner:
// def getRandElemO[T](arr: Array[T]): Option[T] =
// arr.headOption.flatMap(_ => arr.lift(util.Random.nextInt(arr.length)))
score:41
import scala.util.Random
val A = List(1, 2, 3, 4, 5, 6)
A(Random.nextInt(A.size))
score:92
import scala.util.Random
val A = Array("please", "help", "me")
Random.shuffle(A.toList).head
Source: stackoverflow.com
Related Query
- How to choose a random element from an array in Scala?
- How to get a random element from a Set in Scala
- How to efficiently select a random element from a Scala immutable HashSet
- How to use an array inside another array in scala in order to use each element from one array to append to corresponding element from other array?
- how to get all element from array of arrays of spark dataframe column scala
- How to get last element of an array in scala
- How can I idiomatically "remove" a single element from a list in Scala and close the gap?
- How to create a Row from a List or Array in Spark using Scala
- Simple scala code: Returning first element from string array
- Removing nth element from a String Array in Scala
- How can I select a non-sequential subset elements from an array using Scala and Spark?
- How to return multiple random elements from List scala
- How to Random Choice element from Enum Scala3
- How to efficiently pick a random element from an enumeration in scala?
- How to read an element from a Scala HList?
- How to pick a random value from a collection in Scala
- Drop every Nth element from a Scala Array
- How to randomly choose element in array column of different size?
- Scala - Safely get element from multidimensional array
- How to append a letter to every element in an Array in scala
- How to do this in Scala way: get the first element from Option[Seq[String]]
- Scala Play Json - how to read a single element from a element in an Array?
- Scala how to repeat the first element of Array until Array.size reach a certain number
- how to use an array element as a for loop index variable in scala
- How to get the final element of a hierarchical array in scala and apply aggregate functions on it?
- how to remove every nth element from the Scala list?
- How can I write a typeclass in scala on a container type, returning an element from the container?
- How to get each double element from scala Iterator[(Double, Double)]
- How to return Kth smallest/largest element from an array using quicksort's pivot?
- Scala - How to select the last element from an RDD?
More Query from same tag
- Refine a string to only certain values scala
- How to use Scaldi Conditions to do default binding
- How to transform a tuple per RDD to another to group protocol data?
- What features of Scala cannot be translated to Java?
- Scala: How can I catch an exception thrown by a parent class's constructor?
- How to add listeners to javafx UI component with scala
- Task not Serializable exception on converting dataset to red
- Scala Future + sleep runs slower and slower
- What should I use instead deprecated FlinkKafkaConsumer? Scala Flink
- How to add one SBT project as a dependency of another?
- scala : Getting play.api.data.Form[String] required: Option[models.User]
- Scala Refer to a type parameter
- How do I get type parameter from type with type parameter, inside scala macro?
- Error during maven build in Scala-Spark
- Is there a way to combine existentials with typeclasses?
- How to yield a single element from for loop in scala?
- Matching two arrays in Scala
- How does Scalatra send params to the routes?
- Parsing JSON file in Scala
- Why "java.lang.ClassNotFoundException: Failed to find data source: kinesis" with spark-streaming-kinesis-asl dependency?
- Rank a Spark stream dataset column
- How to configure Play! Framework to work with ScalaQuery and H2?
- How can I get a byte that represents an unsigned int in Java?
- Scala : map Dataset[Row] to Dataset[Row]
- Convert Java List to Scala Seq
- How do I use the type member A in IsTraversableLike?
- Why does IntelliJ Idea offer to enclose a string literal to triple double quotes?
- Access field from trait in companion object
- How to find scala java.util.Date difference in minutes?
- Can the 'new' keyword be used on a trait?