sample method Null safety

List<T> sample(
  1. int count,
  2. [Random? random]
)

Selects count elements at random from this iterable.

The returned list contains count different elements of the iterable. If the iterable contains fewer that count elements, the result will contain all of them, but will be shorter than count. If the same value occurs more than once in the iterable, it can also occur more than once in the chosen elements.

Each element of the iterable has the same chance of being chosen. The chosen elements are not in any specific order.

Implementation

List<T> sample(int count, [Random? random]) {
  RangeError.checkNotNegative(count, 'count');
  var iterator = this.iterator;
  var chosen = <T>[];
  for (var i = 0; i < count; i++) {
    if (iterator.moveNext()) {
      chosen.add(iterator.current);
    } else {
      return chosen;
    }
  }
  var index = count;
  random ??= Random();
  while (iterator.moveNext()) {
    index++;
    var position = random.nextInt(index);
    if (position < count) chosen[position] = iterator.current;
  }
  return chosen;
}