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 "functional" way of doing this?
An example could be that I have an array of Int
and want to find all "local minimums.
I could do it sequencially like this
let a = [ 1,2,2,3,5,4,2,5,7,9,5,3,8,10 ]
var i = 1
var r: [Int] = []
while i < a.count - 1 {
if a[i] < a[i+1] && a[i] < a[i-1] {
r.append(i)
}
i += 1
}
print(r)
// [6, 11]
I wonder if there is a more simple or direct way to do it.