For example, there is a Scala array val A = Array(\"please\", \"help\", \"me\")
. How to choose a random element from this array?
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.
def getRandElemO[T](arr: Array[T]): Option[T] =
if (arr.isEmpty) None
else arr lift util.Random.nextInt(arr.length)