Created
July 12, 2024 19:12
-
-
Save gammazero/b92218ba9fda9661cb9ac1a813faceda to your computer and use it in GitHub Desktop.
Compare slices ignoring order of elements
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
// ElementsMatch compares two slices ignoring the order of the elements. If | |
// there are duplicate elements, the number of appearances of each of them in | |
// both lists should match. Empty and nil slices are treated as equal. | |
func ElementsMatch[S ~[]E, E comparable](s1, s2 S) bool { | |
f len(s1) != len(s2) { | |
return false | |
} | |
if len(s1) == 0 && len(s2) == 0 { | |
return true | |
} | |
diff := make(map[E]int, len(s1)) | |
for i := range s1 { | |
diff[s1[i]]++ | |
} | |
for _, v2 := range s2 { | |
if _, ok := diff[v2]; !ok { | |
return false | |
} | |
diff[v2]-- | |
if diff[v2] == 0 { | |
delete(diff, v2) | |
} | |
} | |
return len(diff) == 0 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment