Skip to content

Commit

Permalink
Add Sets Intersection and Union Operations (#48)
Browse files Browse the repository at this point in the history
* update deps

* union and intersection operations added to sets

* tests were added

---------

Co-authored-by: Michael Sverdlov <[email protected]>
Co-authored-by: Michael Sverdlov <[email protected]>
  • Loading branch information
3 people committed Jan 30, 2024
1 parent 99d95aa commit ed421e8
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
26 changes: 26 additions & 0 deletions datastructures/set.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
22 changes: 22 additions & 0 deletions datastructures/set_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
}

0 comments on commit ed421e8

Please sign in to comment.