让我们考虑以下 Array[Array[Int]
val array = Array(Array(7,3,2,1), Array(3,2,5,1), Array(2,1,4,6), Array(1,2,3,4))
我想要这个结果
val sortedArray = Array(Array(1,2,3,4), Array(1,2,3,5), Array(1,2,3,7), Array(1,2,4,6))
如果我们知道每个内部数组具有相同的大小 n 我们开始对每个内部数组进行排序然后使用 sortBy
val sortedArray = array.map(_.sorted).sortBy(x => (x(0), x(1), x(2), x(3)))
不幸的是,如果我们事先不知道内部数组的大小,或者如果它很大,我们将无法如上所示进行。也许可以以动态方式定义自定义排序..
在这种情况下,我也可以做
val sortedArray = array.map(_.sorted).map(a => (a.reduce(_+_), a)).sortBy(_._1).map(_._2)
但它是有效的,因为每个数组中的元素对于每个数组都有一个 uniq 时间。
您可以Ordering
为数组元素实现自己的,例如:
val array = Array(Array(7,3,2,1), Array(3,2,5,1), Array(2,1,4,6), Array(1,2,3,4))
implicit object IntArrayOrdering extends Ordering[Array[Int]] {
override def compare(x: Array[Int], y: Array[Int]): Int =
compareStream(x.toStream, y.toStream)
private def compareStream(x: Stream[Int], y: Stream[Int]): Int = {
(x.headOption, y.headOption) match {
case (Some(xh), Some(yh)) =>
if (xh == yh) {
compareStream(x.tail, y.tail)
} else {
xh.compare(yh)
}
case (Some(_), None) => 1
case (None, Some(_)) => -1
case (None, None) => 0
}
}
}
array.map(_.sorted).sorted
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句