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

前端 未结 6 761
无人及你
无人及你 2020-12-13 23:08

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

6条回答
  •  伪装坚强ぢ
    2020-12-14 00:04

    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)
    

提交回复
热议问题