在 Swift 中对字符串数组进行排序



我有一个这样的大数组:

var tableau = ["Salut", "Hey", "Salut", "Hey", "Hey", "Mom", "Hey", "Dad", "Mom", "Hey", "Plop"]

现在我想要一个数组,每个单词按重复次数排序,所以像这样的数组:

var tableauTrier = ["Hey", "Salut", "Mom", "Dad", "Plop"]

如何使用最少的内存对它们进行排序?请帮帮我!

var tableau = ["Salut", "Hey", "Salut", "Hey", "Hey", "Mom", "Hey", "Dad", "Mom", "Hey", "Plop"]
var counts = [String: Int]()
// generate dictionary of counts for each word
for word in tableau {
    counts[word] = (counts[word] ?? 0) + 1
}
// Sort the tuples based on the count and use map to extract the word
let result = counts.sorted { $0.value > $1.value }.map { $0.key }
print(result)
// ["Hey", "Mom", "Salut", "Plop", "Dad"]
或者 -

只是为了好玩 - 一个带有NSCountedSet的解决方案

let tableau = ["Salut", "Hey", "Salut", "Hey", "Hey", "Mom", "Hey", "Dad", "Mom", "Hey", "Plop"]
let set = NSCountedSet(array: tableau)
let array = (set.allObjects as! [String]).sorted(by: {set.count(for: $0) > set.count(for: $1)})
print(array) 
// [Hey, Mom, Salut, Dad, Plop]

使用一个小的辅助数组,你可以像这样处理它:

var tableau = ["Salut", "Hey", "Salut", "Hey", "Hey", "Mom", "Hey", "Dad", "Mom", "Hey", "Plop"]
var unique = Array(Set(tableau))
unique.sort { (str1, str2) -> Bool in
    let str1Count = tableau.reduce(0, { (result, str) -> Int in
        return  str == str1 ? result+1 : result
    })
    let str2Count = tableau.reduce(0, { (result, str) -> Int in
        return  str == str2 ? result+1 : result
    })
    return str1Count > str2Count
}

这里有一个解决方案:

var result = tableau.sorted(by: { current, next in
    tableau.filter { $0 == current }.count > tableau.filter { $0 == next }.count
}).reduce([String](), {
    if $0.contains($1) {
        return $0
    } else {
        var newPartial = $0
        newPartial.append($1)
        return newPartial
    }
})
print(result)  // ["Hey", "Salut", "Mom", "Dad", "Plop"]

相关内容

  • 没有找到相关文章

最新更新