scalascala-2.8

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


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


Solution

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