I have an array: [1, 2, 3, 4, 5, 6...100]
I am looking to iterate over this array by 5, specifically:
Take the first 5 numbers of the array and get the average, move on to the next 5 numbers and get the average, and so on..
I have tried numerous methods such as a Dequeue and for loops but have not been able to get the outcome desired.
You need to use a progression loop to iterate each 5 element and use reduce to sum the subsequence then divide the total by the subsequence elements count:
let sequence = Array(1...100)
var results: [Double] = []
for idx in stride(from: sequence.indices.lowerBound, to: sequence.indices.upperBound, by: 5) {
let subsequence = sequence[idx..<min(idx.advanced(by: 5), sequence.count)]
let average = Double(subsequence.reduce(0, +)) / Double(subsequence.count)
results.append(average)
}
results // [3, 8, 13, 18, 23, 28, 33, 38, 43, 48, 53, 58, 63, 68, 73, 78, 83, 88, 93, 98]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With