Skip to content

Instantly share code, notes, and snippets.

@SteveAlexander
Last active June 18, 2022 17:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SteveAlexander/cb4484a7aedad7f1c33faa7be755bf76 to your computer and use it in GitHub Desktop.
Save SteveAlexander/cb4484a7aedad7f1c33faa7be755bf76 to your computer and use it in GitHub Desktop.
Weighted shuffle in Dart
import 'dart:math' show Random, pow;
List<T> weightedShuffle<T>(List<T> items, List<num> weights, [Random rng]) {
// See https://softwareengineering.stackexchange.com/questions/233541/how-to-implement-a-weighted-shuffle
// and http://utopia.duth.gr/~pefraimi/research/data/2007EncOfAlg.pdf
assert(items.length == weights.length);
if (rng == null) rng = Random();
final List<double> values = weights
.map<double>((weight) => -pow(rng.nextDouble(), 1 / weight))
.toList(growable: false);
final List<int> order = Iterable<int>.generate(items.length)
.toList(growable: false)
..sort((a, b) => values[a].compareTo(values[b]));
return [for (int i in order) items[i]];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment