pickKind function

HumanErrorKind? pickKind(
  1. Random rng,
  2. Map<HumanErrorKind, double> weights,
  3. Set<HumanErrorKind> applicable
)

O sorteio do tipo: entre os applicable, com o peso de weights (na ordem do enum, para o mesmo Random dar o mesmo tipo). Devolve null se nenhum tipo aplicável tem peso.

Implementation

HumanErrorKind? pickKind(
  Random rng,
  Map<HumanErrorKind, double> weights,
  Set<HumanErrorKind> applicable,
) {
  final total = applicable.fold<double>(0, (s, k) => s + (weights[k] ?? 0));
  if (total <= 0) return null;
  var r = rng.nextDouble() * total;
  HumanErrorKind? last;
  for (final kind in HumanErrorKind.values) {
    final w = applicable.contains(kind) ? (weights[kind] ?? 0) : 0.0;
    if (w <= 0) continue;
    last = kind;
    if (r < w) return kind;
    r -= w;
  }
  return last;
}