把数组中相邻并相同的元素分片

2020-03-22  本文已影响0人  等这姑娘老在我心里
let array: [Int] = [1, 2, 2, 2, 3, 4, 4]
var result: [[Int]] = array.isEmpty ? [] : [[array[0]]]
for (previous, current) in zip(array, array.dropFirst()) {
    print(previous,current)
    if previous == current {
        // 如果相同就加入到同一个数组中
        result[result.endIndex-1].append(current)
    } else {  // 如果不相同 就放到下一个数组中
        result.append([current])
    }
}
result // [[1], [2, 2, 2], [3], [4, 4]]

// 写成通用扩展
extension Array {
    func split(where condition : (Element,Element) -> Bool) ->[[Element]]{
        var result: [[Element]] = self.isEmpty ? [] : [[self[0]]]
        for (previous, current) in zip(self, self.dropFirst()) {
            if condition(previous,current) {
                // f
                result[result.endIndex-1].append(current)
            } else {
                result.append([current])
            }
        }
        return result

    }
}
print(array.split(where:{$0==$1}))
// 简写成
print(array.split(where: ==))
// [[1], [2, 2, 2], [3], [4, 4]]

上一篇 下一篇

猜你喜欢

热点阅读