go - 无序检查 slice 是否相等

标签 go slice equality

我正在尝试找到一种解决方案来检查 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/

相关文章:

go - 如何在 Go 中访问嵌套模块(子模块)?

go - 如何查看UDP IP和端口是否打开

go - 确定 []byte 所需存储的更好方法

java - 如何在 Java 中比较字符串?

c++ - 比较两个无序集合的相等性有多昂贵?

go - 如何在运行例程时将值分配给结构?

python - 如何在不复制引用的情况下在 Python 中对列表进行切片?

python - 以 boolean 值作为索引的数组切片

haskell - haskell中的编程关联性

go - 单 channel 和 select 语句死锁