weightedRandom function

int weightedRandom(
  1. List<double> weights,
  2. Random random
)

Returns a number between [0, weights.length) with probability proportional to the weights

Implementation

int weightedRandom(List<double> weights, Random random) {
  assert(weights.isNotEmpty);

  List<num> cumulativeWeights = weights;
  for (int i = 1; i < weights.length; i++) {
    cumulativeWeights[i] += cumulativeWeights[i - 1];
  }

  // Instead of normalizing, we just use the sum (last cumulative weight) as a factor
  double r = random.nextDouble() * cumulativeWeights.last;
  for (int i = 0; i < weights.length; i++) {
    if (r <= cumulativeWeights[i]) {
      return i;
    }
  }
  return weights.length - 1;
}