zt
09/25/2022, 5:09 AMrandom.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?ephemient
09/25/2022, 8:33 AMfun <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]
}
}