import scala.util.Random class Solution(weights: Array[Int]) { private val totalWeight = weights.sum private val random = new Random() def pickIndex(): Int = { var target = random.nextInt(totalWeight) var i = 0 while (i < weights.length) { target -= weights(i) if (target < 0) { return i } i += 1 } // This line should never be reached as long as the input is valid. -1 } } object Main { def main(args: Array[String]): Unit = { val weights = Array(1, 3, 2, 4) val obj = new Solution(weights) // Perform some random picks val numPicks = 10 for (_ <- 0 until numPicks) { val idx = obj.pickIndex() println(s"Randomly picked index: $idx") } } }import scala.util.Random class Solution(weights: Array[Int]) { private val totalWeight = weights.sum private val random = new Random() def pickIndex(): Int = { var target = random.nextInt(totalWeight) var i = 0 while (i < weights.length) { target -= weights(i) if (target < 0) { return i } i += 1 } // This line should never be reached as long as the input is valid. -1 } } object Main { def main(args: Array[String]): Unit = { val weights = Array(1, 3, 2, 4) val obj = new Solution(weights) // Perform some random picks val numPicks = 10 for (_ <- 0 until numPicks) { val idx = obj.pickIndex() println(s"Randomly picked index: $idx") } } }