我有一个数组:[1, 2, 3, 4, 5, 6...100]
我希望将此数组迭代5,特别是:
获取阵列的前5个数字并得到平均数,然后转到接下来的5个数字并得到平均值,依此类推......
我尝试了很多方法,例如Dequeue
和for循环,但未能获得所需的结果。
答案 0 :(得分:1)
试试这个:
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]
答案 1 :(得分:1)
你需要使用一个进程循环来迭代每个5个元素,并使用reduce来对子序列求和,然后将总数除以子序列元素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]