I'm using CoreMotion's GyroData to determine the Z direction of the devise's movement. This returns me an array of doubles. Positive moving forward, negative moving backwards. I'd now like to count how many times the devise moves in one direction. Moving in opposite direction would be one count.
So I'm trying to count how many times the value changes from a positive to a negative value or from a negative to a positive inside an array. If this is the array the count would be 3.
let array = [1, 2, 3, 4, -1, -1, -2, -3, 1, 2, 3, -1, -2]
Is it possible to do this in one line? I feel like I'm totally over complicating things with this code:
var count = 0
var isPositive = false
for (index, value) in array.enumerated() {
if isPositive == false {
if value > 0 {
isPositive = true
count += 1
}
} else {
if value < 0
isPositive = false
count += 1
}
}
}
Thanks!!