Skip to content

Commit

Permalink
Add set intersection
Browse files Browse the repository at this point in the history
  • Loading branch information
eliben committed Sep 6, 2024
1 parent 368c0a6 commit f1c7990
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 5 deletions.
12 changes: 12 additions & 0 deletions hashset/hashset.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,3 +66,15 @@ func (hs *HashSet[T]) Union(other *HashSet[T]) *HashSet[T] {
}
return result
}

// Intersection returns the set intersection of hs with other. It creates a
// new set.
func (hs *HashSet[T]) Intersection(other *HashSet[T]) *HashSet[T] {
result := New[T]()
for v := range hs.m {
if other.Contains(v) {
result.Add(v)
}
}
return result
}
24 changes: 19 additions & 5 deletions hashset/hashset_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,16 +96,30 @@ func TestContains(t *testing.T) {
}
}

func TestUnion(t *testing.T) {
func TestSetOperations(t *testing.T) {
hs1 := InitWith(10, 20, 30, 40)
hs2 := InitWith(11, 21, 30, 41)

u1 := hs1.Union(hs2)
hs11 := InitWith(11, 21, 30, 41)
u1 := hs1.Union(hs11)
checkAll(t, u1, []int{10, 11, 20, 21, 30, 40, 41})
i1 := hs1.Intersection(hs11)
checkAll(t, i1, []int{30})

u2 := hs1.Union(InitWith(20))
hs22 := InitWith(20)
u2 := hs1.Union(hs22)
checkAll(t, u2, []int{10, 20, 30, 40})
i2 := hs1.Intersection(hs22)
checkAll(t, i2, []int{20})

u3 := hs1.Union(InitWith(90))
hs33 := InitWith(90)
u3 := hs1.Union(hs33)
checkAll(t, u3, []int{10, 20, 30, 40, 90})
i3 := hs1.Intersection(hs33)
checkAll(t, i3, []int{})

hs44 := InitWith(20, 30, 50, 60)
u4 := hs1.Union(hs44)
checkAll(t, u4, []int{10, 20, 30, 40, 50, 60})
i4 := hs1.Intersection(hs44)
checkAll(t, i4, []int{20, 30})
}

0 comments on commit f1c7990

Please sign in to comment.