-
Notifications
You must be signed in to change notification settings - Fork 0
/
set.go
101 lines (81 loc) · 1.88 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
// Package set provides a set implementation written purely in Go and with
// support for basic set operations
package set
// Set implementation
type Set map[interface{}]struct{}
// OrderedPair is used as a tuple for the cartesian product implementation
type OrderedPair struct {
First interface{}
Second interface{}
}
// Exists returns wether a value is present in the set
func (i *Set) Exists(v interface{}) bool {
_, ok := (*i)[v]
return ok
}
// NewSet returns a new initialized instance of Set
func NewSet(elem ...interface{}) *Set {
n := new(Set)
*n = make(Set)
for _, v := range elem {
(*n)[v] = struct{}{}
}
return n
}
// Add inserts a value to the set
func (i *Set) Add(v interface{}) {
(*i)[v] = struct{}{}
}
// Delete removes a value from the set
func (i *Set) Delete(v interface{}) {
delete(*i, v)
}
// Len returns the number of elements in the set
func (i *Set) Len() int {
return len(*i)
}
// Union returns a new set with all the elements the caller has in common
// with s
func (i *Set) Union(s *Set) *Set {
r := NewSet()
for k := range *i {
(*r)[k] = struct{}{}
}
for k := range *s {
(*r)[k] = struct{}{}
}
return r
}
// Intersect returns a new set that contains the common elements of the caller
// with s
func (i *Set) Intersect(s *Set) *Set {
r := NewSet()
for k := range *i {
if _, ok := (*s)[k]; ok {
r.Add(k)
}
}
return r
}
// Complement returns a new set with the elements that exists in the caller but
// not in s
func (i *Set) Complement(s *Set) *Set {
r := NewSet()
for k := range *i {
if _, ok := (*s)[k]; !ok {
r.Add(k)
}
}
return r
}
// CartesianProduct returns the set of all OrderedPairs int the form {A B} so
// that A is an element of the caller and B is an element of s
func (i *Set) CartesianProduct(s *Set) *Set {
r := NewSet()
for p := range *i {
for q := range *s {
r.Add(OrderedPair{p, q})
}
}
return r
}