From ed421e873ebfe53ededb00b9b550e74671538164 Mon Sep 17 00:00:00 2001 From: Noy Shabtay <70848358+noyshabtay@users.noreply.github.com> Date: Tue, 30 Jan 2024 17:50:32 +0200 Subject: [PATCH] Add Sets Intersection and Union Operations (#48) * update deps * union and intersection operations added to sets * tests were added --------- Co-authored-by: Michael Sverdlov Co-authored-by: Michael Sverdlov --- datastructures/set.go | 26 ++++++++++++++++++++++++++ datastructures/set_test.go | 22 ++++++++++++++++++++++ 2 files changed, 48 insertions(+) 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()) +}