gpt4 book ai didi

arrays - 获取数组排序的索引

转载 作者:搜寻专家 更新时间:2023-11-01 06:29:42 24 4
gpt4 key购买 nike

将一些较旧的 AS3 代码移植到 Swift 我在代码中遇到了一个障碍......在 AS3 中,你可以让数组排序操作返回排序结果索引的数字数组,例如

var indices = columns[0].sort(Array.RETURNINDEXEDARRAY | Array.CASEINSENSITIVE);

If you specify a value of 8 or Array.RETURNINDEXEDARRAY for the sortOptions argument of the ...args parameter, Flash returns a sorted numeric array of the indices that reflects the results of the sort and does not modify the array. (AS3 API)

Swift 4 中有任何可用的解决方案可以给我排序的索引吗?

最佳答案

您可以枚举数组,按元素排序并映射元素偏移量:

let array = [1,3,2,5,4]
let sortedIndices = array.enumerated()
.sorted{ $0.element < $1.element }
.map{ $0.offset }
sortedIndices // [0, 2, 1, 4, 3]

如果您愿意,您还可以扩展 Collection 并实现您自己的方法,前提是您将其元素限制为 Comparable 协议(protocol):

extension Collection where Element: Comparable {
func sortedIndices() -> [Int] {
return enumerated()
.sorted{ $0.element < $1.element }
.map{ $0.offset }
}
}

let array = [1,3,2,5,4]
let sortedIndices = array.sortedIndices()
sortedIndices // [0, 2, 1, 4, 3]

另一种选择是添加一个闭包作为参数以允许排序:

extension Collection where Element: Comparable {
func sortedIndices() -> [Int] {
return sortedIndices(by: <)
}
}
extension Collection {
func sortedIndices(by condition: (Element, Element) -> Bool) -> [Int] {
return enumerated()
.sorted{ condition($0.element,$1.element) }
.map{ $0.offset }
}
}

let array = [1,3,2,5,4]
let sortedIndices = array.sortedIndices(by: >)
sortedIndices // [3, 4, 1, 2, 0]

关于arrays - 获取数组排序的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49144009/

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