Skip to content

Commit

Permalink
sets: add Union()
Browse files Browse the repository at this point in the history
  • Loading branch information
marco-m-pix4d committed Sep 25, 2024
1 parent 06c37a7 commit 88f6dce
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 0 deletions.
12 changes: 12 additions & 0 deletions sets/sets.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,3 +105,15 @@ func (s *Set[T]) Intersection(x *Set[T]) *Set[T] {
}
return result
}

// Union returns a set containing all the elements of s and x.
func (s *Set[T]) Union(x *Set[T]) *Set[T] {
result := New[T](max(s.Size(), x.Size()))
for item := range s.items {
result.items[item] = struct{}{}
}
for item := range x.items {
result.items[item] = struct{}{}
}
return result
}
59 changes: 59 additions & 0 deletions sets/sets_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,65 @@ func TestIntersection(t *testing.T) {
}
}

func TestUnion(t *testing.T) {
type testCase struct {
name string
s *sets.Set[int]
x *sets.Set[int]
wantList []int
}

test := func(t *testing.T, tc testCase) {
result := tc.s.Union(tc.x)
sorted := result.OrderedList()

qt.Assert(t, qt.DeepEquals(sorted, tc.wantList))
}

testCases := []testCase{
{
name: "both empty",
s: sets.From[int](),
x: sets.From[int](),
wantList: []int{},
},
{
name: "empty x",
s: sets.From(1, 2),
x: sets.From[int](),
wantList: []int{1, 2},
},
{
name: "empty s",
s: sets.From[int](),
x: sets.From(1, 2),
wantList: []int{1, 2},
},
{
name: "identical",
s: sets.From(1, 2),
x: sets.From(1, 2),
wantList: []int{1, 2},
},
{
name: "all different",
s: sets.From(1, 3),
x: sets.From(2, 4),
wantList: []int{1, 2, 3, 4},
},
{
name: "partial overlap",
s: sets.From(1, 3),
x: sets.From(3, 5),
wantList: []int{1, 3, 5},
},
}

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) { test(t, tc) })
}
}

func TestRemoveFound(t *testing.T) {
type testCase struct {
name string
Expand Down

0 comments on commit 88f6dce

Please sign in to comment.