https://kotlinlang.org logo
#getting-started
Title
# getting-started
z

zt

09/25/2022, 5:09 AM
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

ephemient

09/25/2022, 8:33 AM
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]
    }
}
2 Views