如果你想将给定元素的出现带到n,你可以写这样的东西。
extension Array where Element == String {
func updated(numOccurrencies: Int, ofWord word: String) -> [String] {
let currentOccurrencies = self.filter { $0 == word }.count
let delta = numOccurrencies - currentOccurrencies
if delta > 0 {
let newOccurrencies = Array<String>(repeatElement(word, count: delta))
return self + newOccurrencies
}
if delta < 0 {
var numElmsToDelete = -delta
return filter {
guard $0 == word else { return true }
guard numElmsToDelete > 0 else { return true }
numElmsToDelete -= 1
return false
}
}
return self
}
}
示例
现在给你数组
let words = ["a", "a", "b", "c", "c", "c", "d", "d"]
您可以生成一个新数组,将“a”的出现次数设置为不同的值
words.updated(numOccurrencies: 0, ofWord: "a")
// ["b", "c", "c", "c", "d", "d"]
words.updated(numOccurrencies: 1, ofWord: "a")
// ["a", "b", "c", "c", "c", "d", "d"]
words.updated(numOccurrencies: 2, ofWord: "a")
// ["a", "a", "b", "c", "c", "c", "d", "d"]
words.updated(numOccurrencies: 3, ofWord: "a")
// ["a", "a", "b", "c", "c", "c", "d", "d", "a"]
words.updated(numOccurrencies: 4, ofWord: "a")
// ["a", "a", "b", "c", "c", "c", "d", "d", "a", "a"]
排序
如您所见,新出现的“a”广告添加在数组末尾。如果您希望数组保持排序,只需将 .sorted() 附加到每个调用
words.updated(numOccurrencies: 4, ofWord: "a").sorted()
// ["a", "a", "a", "a", "b", "c", "c", "c", "d", "d"]
“我希望单个字符串在数组中的最大次数为 10 次”
我现在假设必须对输出数组进行排序。
我将为此使用不同的方法。我将为每个单词计算我们期望该单词在输出数组中出现的次数。
每次出现次数将是该单词的 10 次和当前出现次数之间的最小值。
例子
a: min(10, 2) = 2
b: min(10, 1) = 1
...
一旦有了每个单词的预期出现次数,我就可以从头开始构建最终的排序数组。
extension Array where Element == String {
func updated(withMaximumOccurrencies max: Int) -> [String] {
let countedSet = NSCountedSet(array: self)
let uniqueWords = Set(self)
return uniqueWords
.reduce([String]()) { (res, word) -> [String] in
let occurrencies = Swift.min(max, countedSet.count(for: word))
return res + [String](repeatElement(word, count: occurrencies))
}.sorted()
}
}
示例
let words: [String] = ["a", "a", "b", "c", "c", "c", "d", "d"]
words.updated(withMaximumOccurrencies: 1)
["a", "b", "c", "d"]
words.updated(withMaximumOccurrencies: 2)
["a", "a", "b", "c", "c", "d", "d"]
words.updated(withMaximumOccurrencies: 10)
["a", "a", "b", "c", "c", "c", "d", "d"]