Skip to content

Instantly share code, notes, and snippets.

@rodmoioliveira
Last active November 19, 2021 07:41
Show Gist options
  • Select an option

  • Save rodmoioliveira/65281facd4117c37957a2373c5323892 to your computer and use it in GitHub Desktop.

Select an option

Save rodmoioliveira/65281facd4117c37957a2373c5323892 to your computer and use it in GitHub Desktop.
Basic set operations in Golang
// https://rm-o.netlify.app/blog/basic-set-operations-in-golang/
package main
import (
"fmt"
"strings"
)
type (
SetItem interface{}
SetSlice []SetItem
Set map[SetItem]membership
membership struct{}
)
func MakeSet(si ...SetItem) (s Set) {
s = make(map[SetItem]membership)
for _, v := range si {
s[v] = membership{}
}
return
}
func (s Set) Size() int {
return len(s)
}
func (s Set) ToString() string {
r := make([]string, 0, s.Size())
for k := range s {
r = append(r, fmt.Sprintf("%v", k))
}
return fmt.Sprintf("{%v}", strings.Join(r, ","))
}
func (s Set) Contains(si SetItem) (ok bool) {
_, ok = s[si]
return
}
func (s Set) Union(other Set) (set Set) {
set = MakeSet()
for k := range s {
set[k] = membership{}
}
for k := range other {
set[k] = membership{}
}
return
}
func (s Set) Intersection(other Set) (set Set) {
set = MakeSet()
for k := range s {
if ok := other.Contains(k); ok {
set[k] = membership{}
}
}
return
}
func (s Set) Difference(other Set) (set Set) {
set = MakeSet()
for k := range s {
if ok := other.Contains(k); !ok {
set[k] = membership{}
}
}
return
}
func (s Set) SymmetricDifference(other Set) (set Set) {
set = MakeSet()
for k := range s {
if ok := other.Contains(k); !ok {
set[k] = membership{}
}
}
for k := range other {
if ok := s.Contains(k); !ok {
set[k] = membership{}
}
}
return
}
func (s Set) SubsetOf(other Set) bool {
if s.Size() > other.Size() {
return false
}
for k := range s {
if _, exists := other[k]; !exists {
return false
}
}
return true
}
func main() {
set := MakeSet("cat", "cat", "frog", "dog", "cow")
fmt.Println(set.ToString()) // {frog,dog,cow,cat}
fmt.Println(set.ToString()) // {dog,cow,cat,frog}
set = MakeSet("cat", "dog", "cow")
ok := set.Contains("cat")
fmt.Println(ok) // true
ok = set.Contains("buffalo")
fmt.Println(ok) // false
A := MakeSet("cat", "dog", "cow")
B := MakeSet("cat", "duck", "bull")
U := A.Union(B)
fmt.Println(U.ToString())
// {cat,dog,cow,duck,bull}
A = MakeSet("cat", "dog", "cow")
B = MakeSet("cat", "duck", "bull")
I := A.Intersection(B)
fmt.Println(I.ToString())
// {cat}
A = MakeSet("cat", "dog", "cow")
B = MakeSet("cat", "duck", "bull")
D := A.Difference(B)
fmt.Println(D.ToString())
// {dog,cow}
A = MakeSet("cat", "dog", "cow")
B = MakeSet("cat", "duck", "bull")
SD := A.SymmetricDifference(B)
fmt.Println(SD.ToString())
// {dog,cow,duck,bull}
A = MakeSet("cat", "dog", "cow")
B = MakeSet("cat", "dog")
fmt.Println(B.SubsetOf(A)) // true
fmt.Println(A.SubsetOf(B)) // false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment