如何只在数组中保留X个重复项?

时间:2015-09-20 20:13:30

标签: ios arrays swift duplicates

我试图在一个数组中最多只保留8个重复项。我通过S.O.找到了问题如何从数组中过滤重复项,但我不知道如何在数组中保持最多8个。 知道如何实现这个目标吗?

以下是我用来过滤重复项的代码:

func removeDuplicates(array: [String]) -> [String] {
    var encountered = Set<String>()
    var result: [String] = []
    for value in array {
        if encountered.contains(value) {
            // Do not add a duplicate element.
        }
        else {
            // Add value to the set.
            encountered.insert(value)
            // ... Append the value.
            result.append(value)
        }
    }
    return result
}

我希望计算重复次数,以及是否&lt; =某些选定的数字,以保留它们。

2 个答案:

答案 0 :(得分:1)

我建议将它放在数组扩展中,这样它就可以用于任何类型的内容 - Ints,Strings,自定义对象等等。

extension Array where Element: Hashable
{
    /// Returns a copy of `self` with at most `maxOccurrences` occurrences of any element.
    @warn_unused_result
    func removeDuplicates(maxOccurrences maxOccurrences: Int = 1) -> [Element]
    {
        var result: [Element] = []
        var occurrences: [Element: Int] = [:]
        for value in self {
            let count = occurrences[value] ?? 0
            if count >= maxOccurrences { continue }
            result.append(value)
            occurrences[value] = count + 1
        }
        return result
    }
}

var a = [1, 2, 2, 3, 3, 3]
a.removeDuplicates(maxOccurrences: 0)  // empty
a.removeDuplicates()                   // 1, 2, 3
a.removeDuplicates(maxOccurrences: 2)  // 1, 2, 2, 3, 3
a.removeDuplicates(maxOccurrences: 3)  // 1, 2, 2, 3, 3, 3

答案 1 :(得分:1)

两个类似的解决方案 - 一个是我对地图/字典的原始想法,另一个是Paulw11的计数集的想法

func removeDuplicates(array: [String], times:Int) -> [String] {
    var encountered = [String:Int]()
    var result = [String]()
    for value in array {
        let time = encountered[value] ?? 0
        if time < times {
            encountered[value] = time + 1
            result.append(value)
        }
    }
    return result
}

func removeDuplicates2(array: [String], times:Int) -> [String] {
    let encountered = NSCountedSet()
    var result = [String]()
    for value in array {
        encountered.addObject(value)
        if encountered.countForObject(value) <= times {
            result.append(value)
        }
    }
    return result
}

print(removeDuplicates(["", "1", "", "", "1", "1"], times: 2))
print(removeDuplicates2(["", "1", "", "", "1", "1"], times: 2))

输出

  

[&#34;&#34;,&#34; 1&#34;,&#34;&#34;,&#34; 1&#34;]
  [&#34;&#34;,&#34; 1&#34;,&#34;&#34;,&#34; 1&#34;]