Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

sets: add sets intersection #155

Merged
merged 2 commits into from
May 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions sets/sets.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,26 @@ func (s *Set[T]) Remove(item T) bool {
// Difference returns a set containing the elements of s that are not in x.
func (s *Set[T]) Difference(x *Set[T]) *Set[T] {
result := New[T](max(0, s.Size()-x.Size()))
for i := range s.items {
if !x.Contains(i) {
result.items[i] = struct{}{}
for item := range s.items {
if !x.Contains(item) {
result.items[item] = struct{}{}
}
}
return result
}

// Intersection returns a set containing the elements that are both in s and x.
func (s *Set[T]) Intersection(x *Set[T]) *Set[T] {
result := New[T](0)
// loop over the smaller set (thanks to https://github.com/deckarep/golang-set)
smaller := s
bigger := x
if smaller.Size() > bigger.Size() {
smaller, bigger = bigger, smaller
}
for item := range smaller.items {
if bigger.Contains(item) {
result.items[item] = struct{}{}
}
}
return result
Expand Down
59 changes: 59 additions & 0 deletions sets/sets_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,65 @@ func TestDifference(t *testing.T) {
}
}

func TestIntersection(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.Intersection(tc.x)
sorted := result.OrderedList()

assert.DeepEqual(t, sorted, tc.wantList)
}

testCases := []testCase{
{
name: "both empty",
s: sets.From[int](),
x: sets.From[int](),
wantList: []int{},
},
{
name: "empty x returns empty",
s: sets.From(1, 2, 3),
x: sets.From[int](),
wantList: []int{},
},
{
name: "nothing in common returns empty",
s: sets.From(1, 2, 3),
x: sets.From(4, 5),
wantList: []int{},
},
{
name: "one in common",
s: sets.From(1, 2, 3),
x: sets.From(4, 2),
wantList: []int{2},
},
{
name: "s subset of x returns s",
s: sets.From(1, 2, 3),
x: sets.From(1, 2, 3, 12),
wantList: []int{1, 2, 3},
},
{
name: "x subset of s returns x",
s: sets.From(1, 2, 3, 12),
x: sets.From(1, 2, 3),
wantList: []int{1, 2, 3},
},
}

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
Loading