根据匹配数对数组排序

时间:2018-10-12 18:25:40

标签: swift

我正在尝试查找多个测试数组和一个控制数组之间的数组项匹配数。找到匹配数之后,我想将测试数组追加到另一个数组,并按控件数组和测试数组之间的匹配数进行排序。例如,具有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*/

3 个答案:

答案 0 :(得分:3)

这可以通过编写用于处理输入数组的管道以非常实用和快捷的方式完成:

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

原始解决方案的另一种样式更改是对元组组件使用标签,这使代码更清晰,但也更冗长。

答案 1 :(得分:0)

一种选择是将每个数组转换为Set并找到与controlArray相交的元素数。

let controlArray = ["milk", "honey"]
let test1 = ["honey", "water"]
let test2 = ["milk", "honey", "eggs"]
var sortedArrayBasedOnMatches = [ test1, test2 ].sorted { (arr1, arr2) -> Bool in
    return Set(arr1).intersection(controlArray).count > Set(arr2).intersection(controlArray).count
}
print(sortedArrayBasedOnMatches)

答案 2 :(得分:0)

这将涵盖以下情况:元素在您的控制数组中(例如牛奶,牛奶,蜂蜜...)和任何数量的测试数组都不是唯一的。

func sortedArrayBasedOnMatches(testArrays:[[String]], control: [String]) -> [[String]]{
var final = [[String]].init()
var controlDict:[String: Int] = [:]
var orderDict:[Int: [[String]]] = [:] // the value is a array of arrays because there could be arrays with the same amount of matches.
for el in control{
    if controlDict[el] == nil{
        controlDict[el] = 1
    }
    else{
        controlDict[el] = controlDict[el]! + 1
    }
}
for tArr in testArrays{
    var totalMatches = 0
    var tDict = controlDict
    for el in tArr{
        if tDict[el] != nil && tDict[el] != 0 {
            totalMatches += 1
            tDict[el] = tDict[el]! - 1
        }
    }
    if orderDict[totalMatches] == nil{
        orderDict[totalMatches] = [[String]].init()
    }
    orderDict[totalMatches]?.append(tArr)
}
for key in Array(orderDict.keys).sorted(by: >) {
    for arr in orderDict[key]! {
        final.append(arr)
    }
}
    return final
}