dag: Set difference

This commit is contained in:
Mitchell Hashimoto 2017-02-02 10:03:20 -08:00
parent 66b9a6e8e7
commit 77c445a838
No known key found for this signature in database
GPG Key ID: 744E147AA52F5B0A
2 changed files with 78 additions and 0 deletions

View File

@ -48,6 +48,9 @@ func (s *Set) Include(v interface{}) bool {
// Intersection computes the set intersection with other.
func (s *Set) Intersection(other *Set) *Set {
result := new(Set)
if s == nil {
return result
}
if other != nil {
for _, v := range s.m {
if other.Include(v) {
@ -59,6 +62,25 @@ func (s *Set) Intersection(other *Set) *Set {
return result
}
// Difference returns a set with the elements that s has but
// other doesn't.
func (s *Set) Difference(other *Set) *Set {
result := new(Set)
if s != nil {
for k, v := range s.m {
var ok bool
if other != nil {
_, ok = other.m[k]
}
if !ok {
result.Add(v)
}
}
}
return result
}
// Len is the number of items in the set.
func (s *Set) Len() int {
if s == nil {

56
dag/set_test.go Normal file
View File

@ -0,0 +1,56 @@
package dag
import (
"fmt"
"testing"
)
func TestSetDifference(t *testing.T) {
cases := []struct {
Name string
A, B []interface{}
Expected []interface{}
}{
{
"same",
[]interface{}{1, 2, 3},
[]interface{}{3, 1, 2},
[]interface{}{},
},
{
"A has extra elements",
[]interface{}{1, 2, 3},
[]interface{}{3, 2},
[]interface{}{1},
},
{
"B has extra elements",
[]interface{}{1, 2, 3},
[]interface{}{3, 2, 1, 4},
[]interface{}{},
},
}
for i, tc := range cases {
t.Run(fmt.Sprintf("%d-%s", i, tc.Name), func(t *testing.T) {
var one, two, expected Set
for _, v := range tc.A {
one.Add(v)
}
for _, v := range tc.B {
two.Add(v)
}
for _, v := range tc.Expected {
expected.Add(v)
}
actual := one.Difference(&two)
match := actual.Intersection(&expected)
if match.Len() != expected.Len() {
t.Fatalf("bad: %#v", actual.List())
}
})
}
}