I am trying to find a solution to check for equality in 2 slices. Unfortanely, the answers I have found require values in the slice to be in the same order. For example, http://play.golang.org/p/yV0q1_u3xR evaluates equality to false.
I want a solution that lets []string{"a","b","c"} == []string{"b","a","c"}
evaluate to true
.
MORE EXAMPLES[]string{"a","a","c"} == []string{"c","a","c"}
>>> false
[]string{"z","z","x"} == []string{"x","z","z"}
>>> true
无顺序检查切片是否相等
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
4条回答 默认 最新
- dtz8044 2016-03-15 00:35关注
Here is an alternate solution, though perhaps a bit verbose:
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) } } if len(diff) == 0 { return true } return false }
Try it on the <kbd>Go Playground</kbd>
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥16 Qphython 用xlrd读取excel报错
- ¥15 单片机学习顺序问题!!
- ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
- ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
- ¥15 相敏解调 matlab
- ¥15 求lingo代码和思路
- ¥15 公交车和无人机协同运输
- ¥15 stm32代码移植没反应
- ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
- ¥100 连续两帧图像高速减法