Last active
June 18, 2022 17:56
-
-
Save SteveAlexander/cb4484a7aedad7f1c33faa7be755bf76 to your computer and use it in GitHub Desktop.
Weighted shuffle in Dart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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