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>
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 孟德尔随机化结果不一致
- ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
- ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
- ¥15 谁有desed数据集呀
- ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
- ¥15 关于#hadoop#的问题
- ¥15 (标签-Python|关键词-socket)
- ¥15 keil里为什么main.c定义的函数在it.c调用不了
- ¥50 切换TabTip键盘的输入法
- ¥15 可否在不同线程中调用封装数据库操作的类