Swift数组通过过滤器删除连续数字

时间:2016-10-03 15:08:00

标签: arrays swift filtering

如何编写将从数组中删除连续数字的filter函数。

连续我的意思是1,2,3,4形成序列与1,3,5相反(缺少2和5)。

示例:

let input = [1,2,3,4,8,10,12,19]
//Expected filter function.
let output = [8,10,12,19]

2 个答案:

答案 0 :(得分:2)

您可以使用flatMap作为mapfilter对抗nil:

let output = input.enumerated().flatMap { index, element in
    return index > 0 && input[index - 1] + 1 == element ? nil : element
}

print(output) // [1, 8, 10, 12, 19]

答案 1 :(得分:1)

let input = [1,2,3,4,8,10,12,19]

func filterConsecutive(array: [Int]) -> [Int] {

    guard array.count > 1 else {
        return array
    }

    var result = [Int]()
    for i in 0...array.count-2 {
        let first = array[i]
        let second = array[i+1]
        if second != first + 1 {
            result.append(second)
        }
    }
    return result
}

let result = filterConsecutive(array: input)