我有一个像这样的数组:
array = [[[2,2],[8,8]],[[4,4],[1,1]]]
我想像这样对数组进行排序:
sortedArray = [[[1,1],[2,2]],[[4,4],[8,8]]]
任何人都可以提供有关如何对该数组进行排序的提示或解决方案。
谢谢!
答案 0 :(得分:0)
让我们从这个数组开始:
let array = [[[2,2],[8,8]],[[4,4],[1,1]]]
将其放平,并按每个子数组的第一个元素进行排序:
let flat = array.flatMap { $0 }
.sorted { $0.first ?? 0 < $1.first ?? 0 }
现在,我们需要使用以下元素将均匀索引中的每个元素分组:
let start = flat.startIndex
let end = flat.endIndex
let even = stride(from: start, to: end, by: 2).map { flat[$0] }
let odd = stride(from: flat.index(start, offsetBy: 1), to: end, by: 2).map { flat[$0] }
let zipped = zip(even, odd)
let newArray = zipped.map { [$0.0, $0.1]}
现在您可以使用结果了:
print(newArray) //[[[1, 1], [2, 2]], [[4, 4], [8, 8]]]
从偶数和奇数索引的元素创建对的更有效方法是使用this的matt精美扩展:
extension Sequence {
func clump(by clumpsize:Int) -> [[Element]] {
let slices : [[Element]] = self.reduce(into:[]) {
memo, cur in
if memo.count == 0 {
return memo.append([cur])
}
if memo.last!.count < clumpsize {
memo.append(memo.removeLast() + [cur])
} else {
memo.append([cur])
}
}
return slices
}
}
并像这样使用它:
let array = [[[2,2],[8,8]],[[4,4],[1,1]]]
let flat = array.flatMap { $0 }
.sorted { $0.first ?? 0 < $1.first ?? 0 }
let newArray = flat.clump(by: 2)
print(newArray) //[[[1, 1], [2, 2]], [[4, 4], [8, 8]]]