Last active
December 11, 2022 20:13
-
-
Save soypat/00eb8392f24c584dc4dccf5383f7488d to your computer and use it in GitHub Desktop.
Set operations for Go.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package sets | |
// a | b | |
func union[T comparable](a, b map[T]struct{}) map[T]struct{} { | |
c := make(map[T]struct{}) | |
for k := range a { | |
c[k] = struct{}{} | |
} | |
for k := range b { | |
c[k] = struct{}{} | |
} | |
return c | |
} | |
// a & b | |
func intersection[T comparable](a, b map[T]struct{}) map[T]struct{} { | |
c := make(map[T]struct{}) | |
if len(a) > len(b) { | |
a, b = b, a // Put smallest map in a to reduce iterations, thanks Mario R. | |
} | |
for k := range a { | |
if _, ok := b[k]; ok { | |
c[k] = struct{}{} | |
} | |
} | |
return c | |
} | |
// a-b | |
func difference[T comparable](a, b map[T]struct{}) map[T]struct{} { | |
c := make(map[T]struct{}) | |
for k := range a { | |
if _, ok := b[k]; !ok { | |
c[k] = struct{}{} | |
} | |
} | |
return c | |
} | |
// a-b | b-a | |
func symdiff[T comparable](a, b map[T]struct{}) map[T]struct{} { | |
c := make(map[T]struct{}) | |
for k := range a { | |
if _, ok := b[k]; !ok { | |
c[k] = struct{}{} | |
} | |
} | |
for k := range b { | |
if _, ok := a[k]; !ok { | |
c[k] = struct{}{} | |
} | |
} | |
return c | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment