Swift: loop over array elements and access previous and next elements

前端 未结 7 2631
庸人自扰
庸人自扰 2021-02-20 14:19

In Swift, I want to loop over an array and compare each element to the previous and/or next. For each comparison I will either produce a new element or nothing. Is there \"funct

7条回答
  •  悲哀的现实
    2021-02-20 15:02

    Generally, one can use dropFirst() and zip() to traverse over adjacent array elements in parallel. Here is a simple example which produces the array of increments between the array elements:

    let a = [ 1, 2, 2, 3, 5, 4, 2, 5, 7, 9, 5, 3, 8, 10 ]
    
    let diffs = zip(a.dropFirst(), a).map(-)
    print(diffs)
    // [1, 0, 1, 2, -1, -2, 3, 2, 2, -4, -2, 5, 2]
    

    To compute the indices of local minima we can iterate over a, a.dropFirst() and a.dropFirst(2) in parallel. enumerated() is used to keep track of the array offsets, and flatMap() (renamed to compactMap() in Swift 4.1) is used to pick only those indices which correspond to a local minimum:

    let a = [ 1, 2, 2, 3, 5, 4, 2, 5, 7, 9, 5, 3, 8, 10 ]
    
    let localMins = zip(a.enumerated().dropFirst(), zip(a, a.dropFirst(2))).flatMap {
        $0.element < $1.0 && $0.element < $1.1 ? $0.offset : nil
    }
    print(localMins) // [6, 11]
    

提交回复
热议问题