SWIFT: Traversing an array element and accessing the previous and next elements

In Swift, I want to loop an array and compare each element with the previous and/or next element. For each comparison, I will generate a new element or something Don’t do it either. Is there such a “functional” way?

An example might be that I have an Int array and want to find all the “local minimums.

I can do this in order

< /p>

let a = [1,2,2,3,5,4,2,5,7,9,5,3,8,10 ]
var i = 1
var r: [Int] = []

while i if a[i] r.append(i)
}
i += 1
}

print(r)
/ / [6, 11]

I want to know if there is an easier or more straightforward way to do this.

Usually, you can use dropFirst() and zip() to traverse adjacent array elements
under parallel. This is a simple example, it produces an incremental array
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 calculate the index of the local minimum, we can iterate a, a.dropFirst()< br>and a.dropFirst(2) in parallel. enumerated() is used to track
using array offset and flatMap() (renamed compactMap() in Swift 4.1)
only those that correspond to the local Exponent of the smallest value:

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]

In Swift, I want to loop an array and compare each element with the previous and/or next element. For each comparison , I will generate a new element or do nothing. Is there such a “functional” way?

An example might be that I have an Int array and want to find all the “local minimums.

I can do this in order

< /p>

let a = [1,2,2,3,5,4,2,5,7,9,5,3,8,10 ]
var i = 1
var r: [Int] = []

while i if a[i] r.append(i)
}
i += 1
}

print(r)
/ / [6, 11]

I want to know if there is an easier or more direct way to do this.

Usually, You can use dropFirst() and zip() to traverse adjacent array elements
under parallel. This is a simple example, which produces an incremental array
array elements:

< p>

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 calculate the index of the local minimum, we can iterate a, a.dropFirst()
and a.dropFirst(2) in parallel. enumerated () is used for tracking
using array offset and flatMap() (renamed to compactMap() in Swift 4.1)
select only those indices that correspond to the 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]

Leave a Comment

Your email address will not be published.