gpt4 book ai didi

swift - 根据匹配数量对数组进行排序

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

我试图找到多个测试数组和一个控制数组之间的数组项匹配数。找到匹配数后,我想将测试数组附加到另​​一个数组,按控制数组和测试数组之间的匹配数排序。例如,具有 3 个匹配项的测试数组将在索引 0 处,2 个匹配项在索引 1 处,依此类推。

let controlArray = ["milk", "honey"]
let test1 = ["honey", "water"]
let test2 = ["milk", "honey", "eggs"]
var sortedArrayBasedOnMatches = [[String]]()

/*I want to append test1 and test2 to sortedArrayBasedOnMatches based on how many items
test1 and test2 have in common with controlArray*/

/*in my example above, I would want sortedArrayBasedOnMatches to equal
[test2, test1] since test 2 has two matches and test 1 only has one*/

最佳答案

这可以通过编写一个管道来处理输入数组,以非常实用和快速的方式完成:

let sortedArrayBasedOnMatches = [test1, test2] // initial unsorted array
.map { arr in (arr, arr.filter { controlArray.contains($0) }.count) } // making pairs of (array, numberOfMatches)
.sorted { $0.1 > $1.1 } // sorting by the number of matches
.map { $0.0 } // getting rid of the match count, if not needed

更新正如@Carpsen90 所指出的,Switf 5 支持count(where:),这减少了第一个map( ) 调用。一个利用这个的解决方案可以写成

// Swift 5 already has this, let's add it for current versions too
#if !swift(>=5)
extension Sequence {
// taken from the SE proposal
// https://github.com/apple/swift-evolution/blob/master/proposals/0220-count-where.md#detailed-design
func count(where predicate: (Element) throws -> Bool) rethrows -> Int {
var count = 0
for element in self {
if try predicate(element) {
count += 1
}
}
return count
}
}
#endif

let sortedArrayBasedOnMatches = [test1, test2] // initial unsorted array
.map { (arr: $0, matchCount: $0.count(where: controlArray.contains)) } // making pairs of (array, numberOfMatches)
.sorted { $0.matchCount > $1.matchCount } // sorting by the number of matches
.map { $0.arr } // getting rid of the match count, if not needed

原始解决方案的另一个风格变化是为元组组件使用标签,这使代码更清晰一些,但也更冗长一些。

关于swift - 根据匹配数量对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52785168/

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