Python has a `random.choices()` method which lets ...
# getting-started
z
Python has a
random.choices()
method which lets you provide a list of options and a list of weights for them. Is there some equivalent way to do that in kotlin?
e
doesn't seem hard to implement
Copy code
fun <E> Iterable<E>.choices(
    count: Int,
    weights: DoubleArray,
    random: Random = Random.Default,
): List<E> {
    val items = toList()
    require(items.size == weights.size)
    var totalWeight = 0.0
    val cumulativeWeights = DoubleArray(weights.size) { i ->
        val weight = weights[i]
        require(weight >= 0.0)
        totalWeight += weight
        totalWeight
    }
    return List(count) {
        val d = random.nextDouble(until = totalWeight)
        var lo = 0
        var hi = cumulativeWeights.size
        while (lo + 1 < hi) {
            val mid = lo + (hi - lo) / 2
            if (d < cumulativeWeights[mid]) hi = mid else lo = mid + 1
        }
        items[lo]
    }
}