pickMapValue<K, V> static method

V pickMapValue<K, V>(
  1. Map<K, V> map, {
  2. List<double>? weights,
})

Generates a random item from a map's values, optionally using weighted probabilities.

Implementation

static V pickMapValue<K, V>(Map<K, V> map, {List<double>? weights}) {
  if (map.isEmpty) throw ArgumentError('Map cannot be empty');
  final values = map.values.toList();
  if (weights == null) {
    return pickOne(values);
  }
  if (weights.length != values.length) {
    throw ArgumentError('Weights length must match Map value count.');
  }
  final rand = math.Random();
  double sum = weights.fold(0.0, (a, b) => a + b);
  double r = rand.nextDouble() * sum;
  for (int i = 0; i < values.length; i++) {
    if (r < weights[i]) return values[i];
    r -= weights[i];
  }
  return values.last;
}