Skip to content

Instantly share code, notes, and snippets.

@bgadrian
Last active April 23, 2024 13:50
Show Gist options
  • Star 77 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save bgadrian/cb8b9344d9c66571ef331a14eb7a2e80 to your computer and use it in GitHub Desktop.
Save bgadrian/cb8b9344d9c66571ef331a14eb7a2e80 to your computer and use it in GitHub Desktop.
How to implement a simple set data structure in golang
type Set struct {
list map[int]struct{} //empty structs occupy 0 memory
}
func (s *Set) Has(v int) bool {
_, ok := s.list[v]
return ok
}
func (s *Set) Add(v int) {
s.list[v] = struct{}{}
}
func (s *Set) Remove(v int) {
delete(s.list, v)
}
func (s *Set) Clear() {
s.list = make(map[int]struct{})
}
func (s *Set) Size() int {
return len(s.list)
}
func NewSet() *Set {
s := &Set{}
s.list = make(map[int]struct{})
return s
}
//optional functionalities
//AddMulti Add multiple values in the set
func (s *Set) AddMulti(list ...int) {
for _, v := range list {
s.Add(v)
}
}
type FilterFunc func(v int) bool
// Filter returns a subset, that contains only the values that satisfies the given predicate P
func (s *Set) Filter(P FilterFunc) *Set {
res := NewSet()
for v := range s.list {
if P(v) == false {
continue
}
res.Add(v)
}
return res
}
func (s *Set) Union(s2 *Set) *Set {
res := NewSet()
for v := range s.list {
res.Add(v)
}
for v := range s2.list {
res.Add(v)
}
return res
}
func (s *Set) Intersect(s2 *Set) *Set {
res := NewSet()
for v := range s.list {
if s2.Has(v) == false {
continue
}
res.Add(v)
}
return res
}
// Difference returns the subset from s, that doesn't exists in s2 (param)
func (s *Set) Difference(s2 *Set) *Set {
res := NewSet()
for v := range s.list {
if s2.Has(v) {
continue
}
res.Add(v)
}
return res
}
mySet := NewSet()
fmt.Println("has 5", mySet.Has(5)) //false
mySet.Add(5)
fmt.Println("has 5", mySet.Has(5)) //true
mySet.Remove(5)
fmt.Println("has 5", mySet.Has(5)) //false
mySet.AddMulti(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
p := func(v int) bool { return v >= 5 }
subSet := mySet.Filter(p)
fmt.Println("all >= 5", subSet)
@andrewnguyen22
Copy link

Great work! Another option would be to add an alias to the map type as opposed to wrapping it into a struct
type set map[int]struct{}

That way you don't have to do set.list you can jsut use set as the map directly!

@DarrienG
Copy link

Every time I see you can't implement range on a custom type, it makes me sad :(

@bgadrian
Copy link
Author

bgadrian commented Aug 29, 2019 via email

@sumitasok
Copy link

I am not clear whether you said you prefer to use the alias, but can't due to limitations. So I am adding my two cents here.

type Set map[int]bool

func (s *Set) Add(val int) {
	(*s)[val] = true
}

(*s)[val] = true

You can use the same Set instead of creating a new Set

Tests

import "testing"

func TestSet_Add(t *testing.T) {
	type args struct {
		val int
	}
	tests := []struct {
		name string
		s    Set
		args args
		wantCount int
	}{
		{name: "AddOne", s: Set{'s': true}, args: args{val: 'p'}, wantCount: 2},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			tt.s.Add(tt.args.val)
			if len(tt.s) != tt.wantCount {
				t.Errorf("wanted to have %v, got %v", tt.wantCount, len(tt.s))
			}
		})
	}
}

@parthokr
Copy link

func (s *Set) iter() []int {
var keys []int
for k, _ := range s.list {
keys = append(keys, k)
}
return keys
}

and
for _, v := range mySet.iter() {
fmt.Println(v)
}

would be a nice addition

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment