我正在尝试找到一种解决方案来检查 2 个 slice 是否相等。不幸的是,我找到的答案要求 slice 中的值具有相同的顺序。例如,http://play.golang.org/p/yV0q1_u3xR将相等性评估为 false。
我想要一个解决方案,让 []string{"a","b","c"} == []string{"b","a","c"}
评估为 true
.
更多示例
[]string{"a","a","c"} == []string{"c","a","c"}
>>> false
[]string{"z","z","x"} == []string{"x","z","z"}
>>> true
最佳答案
这是一个替代解决方案,虽然可能有点冗长:
func sameStringSlice(x, y []string) bool {
if len(x) != len(y) {
return false
}
// create a map of string -> int
diff := make(map[string]int, len(x))
for _, _x := range x {
// 0 value for int is 0, so just increment a counter for the string
diff[_x]++
}
for _, _y := range y {
// If the string _y is not in diff bail out early
if _, ok := diff[_y]; !ok {
return false
}
diff[_y] -= 1
if diff[_y] == 0 {
delete(diff, _y)
}
}
return len(diff) == 0
}
在 上试试 Go Playground
关于go - 无序检查 slice 是否相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36000487/