gpt4 book ai didi

sorting - 基于其他排序数组对数组进行排序

转载 作者:行者123 更新时间:2023-11-28 10:25:00 25 4
gpt4 key购买 nike

我有两个相同大小的数组,我对第二个数组进行排序。如何排列第一个以匹配?

基本示例(假设用 Strings 替换 Ints):

var array1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

var array2 = [5, 2, 3, 4, 5, 6, 8, 5, 4, 5, 1]

array2.sort = ({ $0 > $1})

结果:

array2 is now [8, 6, 5, 5, 5, 5, 4, 4, 3, 2, 1]

如何对array1的索引值进行排序以匹配array2?

array1 should now be [6, 5, 0, 4, 7, 9, 3, 8, 2, 1, 0]

最佳答案

Zip2sortedmap

array1 = map(sorted(Zip2(array1, array2), {$0.1 > $1.1}), { $0.0 })

组合过滤器

var array1 = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]
var array2 = [5, 2, 3, 4, 5, 6, 8, 5, 4, 5, 1]

func isEven(x:Int) -> Bool {
return x % 2 == 0
}

let result = map(sorted(filter(Zip2(array1, array2), { isEven($0.1) }), {$0.1 > $1.1}), { $0.0 })
// -> ["6", "5", "3", "8", "1"]

如您所见,该行过于复杂,您可能需要 Array 方法链语法:

let result2 = Array(Zip2(array1, array2))
.filter({ isEven($0.1) })
.sorted({ $0.1 > $1.1 })
.map({ $0.0 })

无论如何,如果您的array2[PFObject],您可以实现如下函数:

func isOpen(restaurant: PFObject, forTime time: String, onDay day: Int) -> Bool {

// return `true` if the restaurant is open, `false` otherwise

}

关于sorting - 基于其他排序数组对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28426150/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com