-
Notifications
You must be signed in to change notification settings - Fork 0
/
generic.go
87 lines (69 loc) · 1.4 KB
/
generic.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
75
76
77
78
79
80
81
82
83
84
85
86
87
package set
type SetType[K comparable, V any] interface {
~map[K]V
}
func Contains[S SetType[K, V], K comparable, V any](s S, k K) bool {
_, ok := s[k]
return ok
}
func Insert[S SetType[K, V], K comparable, V any](s S, k K) {
var v V
s[k] = v
}
func Remove[S SetType[K, V], K comparable, V any](s S, k K) {
delete(s, k)
}
func Union[S SetType[K, V], K comparable, V any](sets ...S) S {
union := make(S)
for _, s := range sets {
for k, v := range s {
union[k] = v
}
}
return union
}
func Intersection[S SetType[K, V], K comparable, V any](sets ...S) S {
intersection := make(S)
if len(sets) == 0 {
return intersection
}
minIdx, minLen := 0, len(sets[0])
for idx, s := range sets {
if len(s) < minLen {
minIdx, minLen = idx, len(s)
}
}
minSet := sets[minIdx]
ITEM_LOOP:
for k, v := range minSet {
for _, s := range sets {
if _, ok := s[k]; !ok {
continue ITEM_LOOP
}
}
intersection[k] = v
}
return intersection
}
func SymmetricDifference[S SetType[K, V], K comparable, V any](sets ...S) S {
symdif := make(S)
for k, v := range Union(sets...) {
cnt := 0
for _, s := range sets {
if _, ok := s[k]; ok {
cnt += 1
}
}
if cnt%2 == 1 {
symdif[k] = v
}
}
return symdif
}
func Elements[S SetType[K, V], K comparable, V any](set S) []K {
elements := make([]K, 0, len(set))
for k := range set {
elements = append(elements, k)
}
return elements
}