diff --git a/nset.go b/nset.go index 086c20f..f13b0be 100644 --- a/nset.go +++ b/nset.go @@ -267,6 +267,39 @@ func (n *NSet[T]) Copy() *NSet[T] { } +func UnionSets[T IntsIf](set1, set2 *NSet[T]) *NSet[T] { + + newSet := NewNSet[T]() + for i := 0; i < BucketCount; i++ { + + b1 := &set1.Buckets[i] + b2 := &set2.Buckets[i] + + //Size bucket + bucketSize := b1.StorageUnitCount + if b2.StorageUnitCount > bucketSize { + bucketSize = b2.StorageUnitCount + } + + newB := &newSet.Buckets[i] + newB.Data = make([]StorageType, bucketSize) + + newB.StorageUnitCount = bucketSize + newSet.StorageUnitCount += bucketSize + + //Union fields of both sets on the new set + for j := 0; j < len(b1.Data); j++ { + newB.Data[j] |= b1.Data[j] + } + + for j := 0; j < len(b2.Data); j++ { + newB.Data[j] |= b2.Data[j] + } + } + + return newSet +} + func NewNSet[T IntsIf]() *NSet[T] { n := &NSet[T]{ diff --git a/nset_test.go b/nset_test.go index f1ca5cc..8f10eda 100755 --- a/nset_test.go +++ b/nset_test.go @@ -67,6 +67,14 @@ func TestNSet(t *testing.T) { n7.Union(n6) AllTrue(t, n6.ContainsAll(4, 7, 100, 1000), !n6.Contains(math.MaxUint32), n7.ContainsAll(4, 7, 100, 1000, math.MaxUint32), n7.StorageUnitCount == n7OldStorageUnitCount+n6.StorageUnitCount) + + //UnionSets + n7 = nset.NewNSet[uint32]() + n7.AddMany(math.MaxUint32) + + unionedSet := nset.UnionSets(n6, n7) + AllTrue(t, !n6.Contains(math.MaxUint32), !n7.ContainsAny(4, 7, 100, 1000), unionedSet.ContainsAll(4, 7, 100, 1000, math.MaxUint32), unionedSet.StorageUnitCount == n6.StorageUnitCount+n7OldStorageUnitCount) + } func TestNSetFullRange(t *testing.T) {