问题描述
我想知道数组中是否有任何方法检查相等性而忽略顺序。到目前为止,我确实找到了这个:
test("test ignoring order"){
assert(Array(1,2,4,5).sameElements(Array(1,5)))
}
但是它失败了,因为顺序不一样:
org.scalatest.exceptions.TestFailedException: scala.Predef.intArrayOps(scala.Array.apply(1,5)).sameElements[Int](scala.Predef.wrapIntArray(scala.Array.apply(1,5))) was false
在阵列内部或外部有什么方法吗?
编辑:我不需要对数组进行排序,我只想比较它们而忽略顺序。
解决方法
以下将对两个数组进行排序,然后将它们等同:
test("test ignoring order"){
assert(Array(1,2,4,5).sorted sameElements Array(1,5).sorted)
}
注意:
- 如果您要处理除
==
以外的其他集合,则可以使用sameElements
代替Array
。 -
array1.toSet == array2.toSet
如果其中一个数组重复,而另一个数组不重复则无法工作。
这按预期工作吗?
import scala.annotation.tailrec
def equalsIgnoringOrder(first:Array[Int],second:Array[Int]) : Boolean = {
def removeAtIndex(i:Int,array: Array[Int]) : Array[Int] = {
val buffer = array.toBuffer
buffer.remove(i)
buffer.toArray
}
@tailrec
def firstEqualSecondRec(i:Int,other:Array[Int]) : Boolean = {
if(other.isEmpty) true
else {
val el = first(i)
val index = other.indexOf(el)
if(index == -1) false
else firstEqualSecondRec(i+1,removeAtIndex(index,other))
}
}
if (first.length != second.length) false
else {
val startingIndex = 0
firstEqualSecondRec(startingIndex,second)
}
}
,
一个简单的递归就可以了。
def isSame[T](arrA:Array[T],arrB:Array[T]) :Boolean =
arrA.length == arrB.length &&
(arrA.isEmpty || isSame(arrA.filterNot(_ == arrA.head),arrB.filterNot(_ == arrA.head)))
但是@Tim的问题是正确的:您对明显而简单的排序解决方案有何异议?