-
Notifications
You must be signed in to change notification settings - Fork 0
/
diff.go
51 lines (44 loc) · 1.13 KB
/
diff.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package golist
// Difference returns the elements in `list` that aren't in `other`.
func (arr *List) Difference(other *List) (*List, error) {
if arr.Type() != other.Type() {
return nil, ErrListsNotOfSameType
} else if arr.Type() == TypeListUnknown {
return nil, ErrTypeNotsupported
}
mb := make(map[interface{}]struct{}, other.Len())
for i := 0; i < other.Len(); i++ {
mb[other.Get(i)] = struct{}{}
}
diff, _ := arr.Copy()
diff.Clear()
for i := 0; i < arr.Len(); i++ {
if _, found := mb[arr.Get(i)]; !found {
diff.Append(arr.Get(i))
}
}
return diff, nil
}
// DifferenceBoth returns the elements that aren't in both lists.
func (arr *List) DifferenceBoth(other *List) (*List, error) {
if arr.Type() != other.Type() {
return nil, ErrListsNotOfSameType
} else if arr.Type() == TypeListUnknown {
return nil, ErrTypeNotsupported
}
diff, _ := arr.Copy()
diff.Clear()
m := map[interface{}]int{}
for i := 0; i < arr.Len(); i++ {
m[arr.Get(i)] = 1
}
for i := 0; i < other.Len(); i++ {
m[other.Get(i)] = m[other.Get(i)] + 1
}
for mKey, mVal := range m {
if mVal == 1 {
diff.Append(mKey)
}
}
return diff, nil
}