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

前端 未结 6 760
无人及你
无人及你 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-13 23:47

    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

提交回复
热议问题