lazyShuffler<T> function
Shuffles a List lazily.
Examples:
var list = [for (var i = 0; i < 1000; i += 1) i];
// Draw 5 random elements from `list`. The rest of `list` will contain the
// remaining elements in an indeterminate order.
var iterator = lazyShuffler(list).iterator;
for (var i = 0; i < 5 && iterator.moveNext(); i += 1) {
print(iterator.current);
}
// Alternatively, if resuming iteration later is unnecessary:
var i = 0;
for (var element in lazyShuffler(list)) {
if (i == 5) {
break;
}
print(element);
}
// Or:
lazyShuffler(list).take(5).forEach(print);
Since advancing the iterator mutates list
, list[i]
in the example
above would have the same value as iterator.current
.
Implementation
Iterable<T> lazyShuffler<T>(List<T> list, {math.Random? random}) sync* {
random ??= math.Random();
for (var nextIndex = 0; nextIndex < list.length; nextIndex += 1) {
var i = random.nextIntFrom(nextIndex, list.length);
list.swap(nextIndex, i);
yield list[nextIndex];
}
}