unionCardinalityN<T> static method
Calculates the cardinality of the union of multiple sets using the Generalized Inclusion-Exclusion Principle.
Formula for n sets: |A₁ ∪ A₂ ∪ ... ∪ Aₙ| = Σ|Aᵢ| - Σ|Aᵢ ∩ Aⱼ| + Σ|Aᵢ ∩ Aⱼ ∩ Aₖ| - ... + (-1)ⁿ⁻¹|A₁ ∩ A₂ ∩ ... ∩ Aₙ|
Note: This implementation is optimized for small numbers of sets (≤ 10). For larger numbers, consider alternative approaches.
Example:
final sets = [
CustomSet<int>([1, 2, 3]),
CustomSet<int>([3, 4, 5]),
CustomSet<int>([5, 6, 7]),
];
print(CardinalityUtils.unionCardinalityN(sets)); // Output: 7
Implementation
static int unionCardinalityN<T>(List<CustomSet<T>> sets) {
if (sets.isEmpty) return 0;
if (sets.length == 1) return sets[0].cardinality;
if (sets.length == 2) return unionCardinality(sets[0], sets[1]);
if (sets.length == 3) return unionCardinality3(sets[0], sets[1], sets[2]);
// For more than 3 sets, compute actual union
CustomSet<T> result = sets[0];
for (int i = 1; i < sets.length; i++) {
result = SetOperations.union(result, sets[i]);
}
return result.cardinality;
}