weightedShuffle<T> function

List<T> weightedShuffle<T>(
  1. List<WeightedItem<T>> items, [
  2. Random? rng
])

Returns the values from items in a random order that respects weights.

Higher-weighted items are more likely to appear earlier in the result. Uses the algorithm: for each item, compute random^(1/weight) and sort descending. This is a well-known weighted random sampling technique.

Matches the TS SDK:

export function weightedShuffle<T>(arr: WeightedItem<T>[]): T[] {
  return arr
    .map(({ value, weight }) => ({
      value,
      weight: Math.pow(Math.random(), 1 / weight),
    }))
    .sort((a, b) => b.weight - a.weight)
    .map((item) => item.value);
}

Implementation

List<T> weightedShuffle<T>(List<WeightedItem<T>> items, [Random? rng]) {
  final random = rng ?? Random();

  final scored = items.map((item) {
    // Avoid division by zero: treat weight 0 as very low priority.
    final w = item.weight > 0 ? item.weight : 1;
    final score = pow(random.nextDouble(), 1.0 / w);
    return _ScoredItem(item.value, score.toDouble());
  }).toList();

  // Sort descending by score — higher scores first.
  scored.sort((a, b) => b.score.compareTo(a.score));

  return scored.map((s) => s.value).toList();
}