我想将一个数组和“镜像”顺序更改排序到同一维度的另一个数组。
问题与此类似,但对于Swift语言: Better way to sort 2 "linked" arrays?
示例:
let arr1 = ["a", "b", "c", "d", "e"]
let arr2 = [1, 5, 9, 2, 3]
... //sort
//result == ["a", "d", "e", "b", c"]
我知道的近似解决方案:
for i in stride(from 0, to: arr2.count - 1, by: 1) {
for j in stride(from i + 1, to: arr2.count, by: 1) {
if arr2[i] > arr2[j] {
...//swap arr2[i] and arr2[j]
...//swap arr1[i] and arr1[j]
}
}
}
但他们为在Swift中使用数组进行高级处理添加了许多其他可能性。那么是否可以使用内部Swift功能简化此解决方案?
注意:arr1
和arr2
作为单独的数组提供。
EDITED
是。您发现了类似的问题,但他们的标题很糟糕,并没有反映出作者需要的答案。换句话说,如果您删除/关闭我的问题,人们可能会继续再次询问,因为无法找到现有标题的内容!
答案 0 :(得分:2)
zip
阵列在一起sort
数组2的新数组 map
数组到数组1
let arr1 = ["a", "b", "c", "d", "e"]
let arr2 = [1, 5, 9, 2, 3]
let result = zip(arr1, arr2) // [("a", 1), ("b", 5), ("c", 9), ("d", 2), ("e", 3)]
.sorted(by: {$0.1 < $1.1}) // [("a", 1), ("d", 2), ("e", 3), ("b", 5), ("c", 9)]
.map{ $0.0 } // ["a", "d", "e", "b", "c"]