-
Notifications
You must be signed in to change notification settings - Fork 318
/
hash_set.go
87 lines (76 loc) · 1.48 KB
/
hash_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
package set
import (
"bytes"
"fmt"
)
type HashSet struct {
m map[interface{}]bool
}
func NewHashSet() *HashSet {
return &HashSet{m: make(map[interface{}]bool)}
}
func (set *HashSet) Add(e interface{}) bool {
if !set.m[e] {
set.m[e] = true
return true
}
return false
}
func (set *HashSet) Remove(e interface{}) {
delete(set.m, e)
}
func (set *HashSet) Clear() {
set.m = make(map[interface{}]bool)
}
func (set *HashSet) Contains(e interface{}) bool {
return set.m[e]
}
func (set *HashSet) Len() int {
return len(set.m)
}
func (set *HashSet) Same(other Set) bool {
if other == nil {
return false
}
if set.Len() != other.Len() {
return false
}
for key := range set.m {
if !other.Contains(key) {
return false
}
}
return true
}
func (set *HashSet) Elements() []interface{} {
initialLen := len(set.m)
snapshot := make([]interface{}, initialLen)
actualLen := 0
for key := range set.m {
if actualLen < initialLen {
snapshot[actualLen] = key
} else {
snapshot = append(snapshot, key)
}
actualLen++
}
if actualLen < initialLen {
snapshot = snapshot[:actualLen]
}
return snapshot
}
func (set *HashSet) String() string {
var buf bytes.Buffer
buf.WriteString("HashSet{")
first := true
for key := range set.m {
if first {
first = false
} else {
buf.WriteString(" ")
}
buf.WriteString(fmt.Sprintf("%v", key))
}
buf.WriteString("}")
return buf.String()
}