Skip to content

Instantly share code, notes, and snippets.

@akhenakh
Created November 3, 2017 18:15
Show Gist options
  • Save akhenakh/7342953ced3f66eab26dcd4b1c3785cd to your computer and use it in GitHub Desktop.
Save akhenakh/7342953ced3f66eab26dcd4b1c3785cd to your computer and use it in GitHub Desktop.
Simple set for Go, could be any type
var exists = struct{}{}
type int64Set struct {
m map[int64]struct{}
}
type stringSet struct {
m map[string]struct{}
}
func newInt64Set(entries ...int64) *int64Set {
s := &int64Set{}
s.m = make(map[int64]struct{})
for _, v := range entries {
s.m[v] = exists
}
return s
}
func (s *int64Set) Len(v int64) int {
return len(s.m)
}
func (s *int64Set) Add(v ...int64) {
for _, k := range v {
s.m[k] = exists
}
}
func (s *int64Set) Remove(v int64) {
delete(s.m, v)
}
func (s *int64Set) Contains(v int64) bool {
_, c := s.m[v]
return c
}
func (s *int64Set) Union(o *int64Set) *int64Set {
a := append(s.ToSlice(), o.ToSlice()...)
us := newInt64Set(a...)
return us
}
func (s *int64Set) Intersect(o *int64Set) (*int64Set, bool) {
si := newInt64Set()
for k := range s.m {
if _, ok := o.m[k]; ok {
si.m[k] = exists
}
}
return si, len(si.m) > 0
}
func (s *int64Set) ToSlice() []int64 {
l := make([]int64, len(s.m))
i := 0
for k := range s.m {
l[i] = k
i++
}
return l
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment