-
Notifications
You must be signed in to change notification settings - Fork 0
/
set_collections.go
103 lines (85 loc) · 1.56 KB
/
set_collections.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
// greedy_algorithm
package main
import (
"fmt"
"strings"
)
type Set struct {
hash map[string]int
arr []string
}
func (set *Set) Add(str string) {
if set.hash == nil {
set.hash = make(map[string]int)
set.arr = make([]string, 0, 20)
}
if _, ok := set.hash[str]; !ok {
set.arr = append(set.arr, str)
set.hash[str] = len(set.arr) - 1
}
}
func (set *Set) AddSlice(sl *[]string) {
for _, val := range *sl {
set.Add(val)
}
}
func (set *Set) Del(str string) {
if i, ok := set.hash[str]; !ok {
set.arr[i] = set.arr[len(set.arr)-1]
set.arr = set.arr[:len(set.arr)-1]
delete(set.hash, str)
}
}
func (set *Set) Size() int {
return len(set.hash)
}
func (set *Set) Has(str string) bool {
_, ok := set.hash[str]
return ok
}
func (set *Set) Clear() {
set.hash = make(map[string]int)
set.arr = make([]string, 0, 20)
}
func (s *Set) Intersection(s2 *Set) *Set {
s3 := Set{}
for i := range s2.hash {
_, ok := s.hash[i]
if ok {
s3.Add(i)
}
}
return &s3
}
func (s *Set) Difference(s2 *Set) *Set {
s3 := Set{}
for _, i := range s.arr {
_, ok := s2.hash[i]
if !ok {
if i == "" {
continue
}
s3.Add(i)
}
}
return &s3
}
func (s *Set) Subset(s2 *Set) bool {
for _, i := range s.arr {
_, ok := s2.hash[i]
if !ok {
return false
}
}
return true
}
func (s *Set) ToString() string {
return strings.Trim(strings.Join(s.arr, ", "), ", ")
}
func Test() {
var set *Set = &Set{}
var set2 *Set = &Set{}
set.AddSlice(&[]string{"q", "w", "e"})
set2.AddSlice(&[]string{"w", "e", "r"})
fmt.Println("*** >>> SeT", set.Difference(set2))
}