sample method

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>[];
  random ??= Random();
  while (chosen.length < count) {
    if (iterator.moveNext()) {
      var nextElement = iterator.current;
      var position = random.nextInt(chosen.length + 1);
      if (position == chosen.length) {
        chosen.add(nextElement);
      } else {
        chosen.add(chosen[position]);
        chosen[position] = nextElement;
      }
    } else {
      return chosen;
    }
  }
  var index = count;
  while (iterator.moveNext()) {
    index++;
    var position = random.nextInt(index);
    if (position < count) chosen[position] = iterator.current;
  }
  return chosen;
}