【问题标题】:Easy way to check an array for contiguous three or more numbers in Swift在 Swift 中检查数组中连续三个或更多数字的简单方法
【发布时间】:2016-03-02 15:27:23
【问题描述】:

是否有任何简单的方法来检查数组是否包含三个或更多的连续值?
例如[4, 2, 1, 1, 1, 7, 4, 4, 4, 4] 包含两个连续的序列 1 和 4。
要检查我希望给出 1 和最小允许共轭,在这种情况下 2,它只会返回 true
谢谢。

【问题讨论】:

  • 已编辑。感谢@Eric D 的更正。

标签: arrays swift2


【解决方案1】:

我们可以首先使用用户@oisdk 在他的回答中对SequenceType 的简洁扩展:

扩展将元组中的连续元素分组(value, numberOfSuccessions)

/* from SO user @oisdk:s answer in Q&A:
   https://stackoverflow.com/a/35325141/4573247 */
extension SequenceType where Generator.Element: Equatable {
    func group() -> [(Generator.Element, Int)] {
        var res: [(Generator.Element, Int)] = []
        for el in self {
            if res.last?.0 == el {
                res[res.endIndex-1].1 += 1
            } else {
                res.append((el,1))
            }
        }
        return res
    }
}

使用它,我们可以快速编写另一个扩展来检查给定数组是否存在连续序列(对于一些最小连续/重复次数):

extension SequenceType where Generator.Element == Int {
    func containsContiguousValue(value: Int, forMinimumRepeats rep: Int) -> Bool {
        return !self
            .group()
            .contains{ (val, count) in count >= rep && val == value }
    }
}

如下使用

/* Example usage */
let array = [4, 2, 1, 1, 1, 7, 4, 4, 4, 4]

array.containsContiguousValue(1, forMinimumRepeats: 3) // true
array.containsContiguousValue(1, forMinimumRepeats: 4) // false
array.containsContiguousValue(4, forMinimumRepeats: 4) // true
array.containsContiguousValue(2, forMinimumRepeats: 3) // false

【讨论】:

    【解决方案2】:

    我认为最简单的方法是借助 reduce 函数。如果您愿意,您可以扩展数据结构,但我不太喜欢这样做。因此,这是您示例的简单解决方案

        // example array
        let a = [4, 2, 1, 1, 1, 7, 4, 4, 4, 4]
    
        let minRepeats = 3      // desired min repeats
        let elementToCheck = 4  // element to check
    
        let m = a.reduce(0) { (initial: Int, el: Int) -> Int in
            if initial >= minRepeats {
                return initial
            } else {
                return el == elementToCheck ? initial + 1 : 0
            }
        }
    
        // if m == minRepeats the check is positive, if m < minRepeats the check is negative
        // let check = a.reduce(0){...} == minRepeats gives you the right result
        // Thanks to user3441734 for the correction
    

    【讨论】:

      【解决方案3】:

      上面的答案很有帮助,但并不像我需要的那样通用。此外,它们有点过时了,所以对于那些遇到这个要求的人,这里有一个通用的可重用 Swift 4.2 实现:

      任何Collection 的扩展,它返回一个范围数组,表示与给定谓词匹配的集合中连续元素的索引。

      https://gist.github.com/shaps80/8ec24f82ad1e54d42709277ec2af93a3

      【讨论】:

        猜你喜欢
        • 2022-11-10
        • 2019-08-30
        • 2016-01-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多