Iterating over an array by range

2019-05-17 03:56发布

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.

2条回答
萌系小妹纸
2楼-- · 2019-05-17 04:32

Try this:

extension Array {
    // Use this extension method to get subArray [[1,2,3,4,5], [6,7,8,9,10],...]
    func chunk(_ chunkSize: Int) -> [[Element]] {
        return stride(from: 0, to: self.count, by: chunkSize).map({ (startIndex) -> [Element] in
            let endIndex = (startIndex.advanced(by: chunkSize) > self.count) ? self.count-startIndex : chunkSize
            return Array(self[startIndex..<startIndex.advanced(by: endIndex)])
        })
    }
}

let arr = Array(1...100)

var result: [Double] = []

for subArr in arr.chunk(5) {
    result.append(subArr.reduce(0.0) {$0 + Double($1) / Double(subArr.count)}) // Use reduce to calculate avarage of numbers in subarray.
}

result // [3.0, 7.9999999999999991, 13.0, 18.0, 23.0, 28.000000000000004, 33.0, 38.0, 43.0, 48.0, 53.0, 58.0, 63.0, 68.0, 73.0, 78.0, 83.0, 88.0, 93.0, 98.0]
查看更多
干净又极端
3楼-- · 2019-05-17 04:43

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]
查看更多
登录 后发表回答