generateCombinations<T, E> function

List<List<E>> generateCombinations<T, E>(
  1. Iterable<T> alphabet,
  2. int minimumSize,
  3. int maximumSize, {
  4. bool allowRepetition = true,
  5. bool checkAlphabet = true,
  6. Iterable<E> mapper(
    1. T e
    )?,
  7. bool validator(
    1. List<E> combination
    )?,
})

Generate combinations using the alphabet elements.

  • alphabet of possible elements per combination.
  • The minimumSize of the generated combinations.
  • The maximumSize of the generated combinations.
  • If allowRepetition is true will allow the repetition of elements for each combination.
  • If checkAlphabet is true it will check if the alphabet has duplicated elements.
  • An optional mapper can be used to expand or map each alphabet element.
  • An optional combination validator.
  • Note that an alphabet can't have duplicated elements.

Implementation

List<List<E>> generateCombinations<T, E>(
    Iterable<T> alphabet, int minimumSize, int maximumSize,
    {bool allowRepetition = true,
    bool checkAlphabet = true,
    Iterable<E> Function(T e)? mapper,
    bool Function(List<E> combination)? validator}) {
  if (minimumSize < 1) minimumSize = 1;

  var combinations = <List<E>>[];
  if (alphabet.isEmpty || maximumSize <= 0) return combinations;

  if (alphabet is! List && alphabet is! Set) {
    alphabet = alphabet.toList();
  }

  if (checkAlphabet && alphabet is! Set<T>) {
    var set = alphabet.toSet();
    if (set.length != alphabet.length) {
      throw ArgumentError('Invalid alphabet: found duplicated element!');
    }
  }

  mapper ??= (e) => <E>[e as E];
  validator ??= (c) => true;

  if (allowRepetition) {
    for (var size = minimumSize; size <= maximumSize; ++size) {
      _fillWithRepetition<T, E>(
          alphabet, <E>[], size, combinations, mapper, validator);
    }
  } else {
    if (maximumSize > alphabet.length) {
      maximumSize = alphabet.length;
    }

    for (var size = minimumSize; size <= maximumSize; ++size) {
      _fillNoRepetition<T, E>(
          alphabet, <E>[], 0, size, combinations, mapper, validator);
    }
  }

  return combinations;
}