-
Notifications
You must be signed in to change notification settings - Fork 0
/
set.go
74 lines (62 loc) · 1.32 KB
/
set.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package utils
type Set[T comparable] map[T]bool
func (s Set[T]) Values() []T {
values := make([]T, 0)
for k := range s {
values = append(values, k)
}
return values
}
func (s Set[T]) Has(value T) bool {
_,ok := s[value]
return ok
}
func (s Set[T]) Add(value T) bool {
s[value] = true
return s[value]
}
func (s Set[T]) Adds(values ...T) bool {
allAdded := true
for _, value := range values {
if !s.Add(value) {
allAdded = allAdded && false
}
}
return allAdded
}
func NewSet[T comparable](value ...T) Set[T] {
set := make(Set[T],0)
for _,val := range value {
set.Add(val)
}
return set
}
// Union 返回两个集合的并集
func (s Set[T]) Union(other Set[T]) Set[T] {
unionSet := NewSet[T]()
for k := range s {
unionSet.Add(k)
}
for k := range other {
unionSet.Add(k)
}
return unionSet
}
func (s Set[T]) Intersection(other Set[T]) Set[T] {
intersectionSet := NewSet[T]()
for k := range s {
if other.Has(k) {
intersectionSet.Add(k)
}
}
return intersectionSet
}
func (s Set[T]) Difference(other Set[T]) Set[T] {
differenceSet := NewSet[T]()
for k := range s {
if !other.Has(k) {
differenceSet.Add(k)
}
}
return differenceSet
}