isPartition<T> static method

bool isPartition<T>(
  1. CustomSet<CustomSet<T>> partitions,
  2. CustomSet<T> original
)

Checks if a collection of sets forms a valid partition of the original set.

A partition of set A is a collection of non-empty subsets A₁, A₂, ... such that:

  1. A₁ ∪ A₂ ∪ ... = A (union equals original)
  2. Aᵢ ∩ Aⱼ = ∅ for i ≠ j (all subsets are pairwise disjoint)

Example:

final original = CustomSet<int>([1, 2, 3, 4, 5, 6, 7, 8]);
final partitions = CustomSet<CustomSet<int>>([
  CustomSet([1]),
  CustomSet([2, 3, 4]),
  CustomSet([5, 6]),
  CustomSet([7, 8]),
]);
print(AdvancedSetOperations.isPartition(partitions, original)); // Output: true

Implementation

static bool isPartition<T>(
  CustomSet<CustomSet<T>> partitions,
  CustomSet<T> original,
) {
  // Check all partitions are non-empty
  for (var partition in partitions.elements) {
    if (partition.isEmpty) return false;
  }

  // Check union of all partitions equals original
  CustomSet<T> unionSet = CustomSet.empty();
  for (var partition in partitions.elements) {
    unionSet = SetOperations.union(unionSet, partition);
  }

  if (!unionSet.equals(original)) return false;

  // Check all partitions are pairwise disjoint
  final partitionList = partitions.elements.toList();
  for (int i = 0; i < partitionList.length; i++) {
    for (int j = i + 1; j < partitionList.length; j++) {
      if (!partitionList[i].isDisjointFrom(partitionList[j])) return false;
    }
  }

  return true;
}