-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathset.go
107 lines (82 loc) · 1.68 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
102
103
104
105
106
107
package mathlib
import (
"fmt"
"strings"
)
// NewSet create a new set from values
func NewSet(values ...interface{}) Set {
newset := Set{}
for _, v := range values {
newset.Add(v)
}
return newset
}
// Set represents a set data type
type Set map[interface{}]bool
// Adds an elemets to the set
func (s Set) Add(i interface{}) {
s[i] = true
}
func (s Set) Remove(i interface{}) {
delete(s, i)
}
// Contains returns true if an element is contained in set
func (s Set) Contains(i interface{}) bool {
return s[i]
}
// Len returns length of the set
func (s Set) Len() int {
return len(s)
}
// String returns a set as a string
func (s Set) String() string {
var values []string
for k := range s {
values = append(values, fmt.Sprintf("%v", k))
}
return "{ " + strings.Join(values, " , ") + " }"
}
// IsSubsetOf returns true if set contains another set
func (s Set) IsSubsetOf(set Set) bool {
// this set is a subset of set provided
for k := range s {
if !set.Contains(k) {
return false
}
}
return true
}
// Union joins two sets together
func (s Set) Union(set Set) Set {
u := Set{}
for s := range s {
u.Add(s)
}
for s := range set {
u.Add(s)
}
return u
}
// Intersection return a set of those elemets that are in both sets
func (s Set) Intersection(set Set) Set {
intersection := Set{}
for k := range s {
if set.Contains(k) {
intersection.Add(k)
}
}
return intersection
}
// Difference returns a set of elements that are in the object set and not in provided set
func (s Set) Difference(set Set) Set {
diff := Set{}
for k := range s {
if !set.Contains(k) {
diff.Add(k)
}
}
return diff
}
func (s Set) Cardinality() int {
return s.Len()
}