diff --git a/datastructures/set.go b/datastructures/set.go index 220ffda..5f7c6df 100644 --- a/datastructures/set.go +++ b/datastructures/set.go @@ -57,3 +57,29 @@ func (set *Set[T]) ToSlice() []T { return slice } + +func (setA *Set[T]) Intersect(setB *Set[T]) *Set[T] { + intersectedSet := MakeSet[T]() + bigSet, smallSet := setB, setA + if setA.Size() > setB.Size() { + bigSet, smallSet = setA, setB + } + + for key := range smallSet.container { + if bigSet.Exists(key) { + intersectedSet.Add(key) + } + } + return intersectedSet +} + +func (setA *Set[T]) Union(setB *Set[T]) *Set[T] { + unionedSet := MakeSet[T]() + for key := range setA.container { + unionedSet.Add(key) + } + for key := range setB.container { + unionedSet.Add(key) + } + return unionedSet +} diff --git a/datastructures/set_test.go b/datastructures/set_test.go index b692cdf..637bbe9 100644 --- a/datastructures/set_test.go +++ b/datastructures/set_test.go @@ -45,3 +45,25 @@ func TestMakeSetFromElements(t *testing.T) { stringSet := MakeSetFromElements(stringSlice...) assert.ElementsMatch(t, stringSet.ToSlice(), stringSlice) } + +func TestSetsIntersection(t *testing.T) { + testSet := generateNewSetWithData() + anotherSet := MakeSet[int]() + intersectedSet := testSet.Intersect(anotherSet) + assert.Equal(t, 0, intersectedSet.Size()) + + anotherSet.Add(3) + intersectedSet = testSet.Intersect(anotherSet) + assert.Equal(t, 1, intersectedSet.Size()) +} + +func TestSetsUnion(t *testing.T) { + testSet := generateNewSetWithData() + anotherSet := MakeSet[int]() + unionedSet := testSet.Union(anotherSet) + assert.Equal(t, 3, unionedSet.Size()) + + anotherSet.Add(4) + unionedSet = testSet.Union(anotherSet) + assert.Equal(t, 4, unionedSet.Size()) +}