generateCombinations<T, E> function
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
istrue
will allow the repetition of elements for each combination. - If
checkAlphabet
istrue
it will check if thealphabet
has duplicated elements. - An optional
mapper
can be used to expand or map eachalphabet
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;
}