How to choose a random element from an array in Scala?
Solution 1:
import scala.util.Random
val A = Array("please", "help", "me")
Random.shuffle(A.toList).head
Solution 2:
import scala.util.Random
val A = List(1, 2, 3, 4, 5, 6)
A(Random.nextInt(A.size))
Solution 3:
import java.util.Random
// ...
val rand = new Random(System.currentTimeMillis())
val random_index = rand.nextInt(A.length)
val result = A(random_index)
Solution 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)))
Solution 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