pickWeighted method

int pickWeighted(
  1. List<int> weights
)

Index into weights (small non-negative integers, sum > 0), chosen with probability proportional to its weight. Integer weights only, so no floating-point cumulative sums can round differently.

Implementation

int pickWeighted(List<int> weights) {
  var total = 0;
  for (final w in weights) {
    if (w < 0) throw ArgumentError.value(weights, 'weights', 'negative');
    total += w;
  }
  if (total <= 0) {
    throw ArgumentError.value(weights, 'weights', 'sum must be > 0');
  }
  var r = nextInt(total);
  for (var i = 0; i < weights.length; i++) {
    r -= weights[i];
    if (r < 0) return i;
  }
  throw StateError('unreachable');
}