2
數組我有一個數組:[1, 2, 3, 4, 5, 6...100]
迭代的範圍
我找了5遍歷數組,具體如下:
在第一個5個號碼的陣列,並獲得平均,移動在接下來的5個數字,並獲得平均值,等等。
我已經嘗試了很多方法,如Dequeue
和for循環,但一直沒有能夠得到所需的結果。
數組我有一個數組:[1, 2, 3, 4, 5, 6...100]
迭代的範圍
我找了5遍歷數組,具體如下:
在第一個5個號碼的陣列,並獲得平均,移動在接下來的5個數字,並獲得平均值,等等。
我已經嘗試了很多方法,如Dequeue
和for循環,但一直沒有能夠得到所需的結果。
您需要使用一個進展循環迭代每5元素,並使用降低求和子序列然後除以所述亞序列元素的總數:
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]
嘗試這種情況:
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]
使用這並計算出平均值https://gist.github.com/ericdke/fa262bdece59ff786fcb – xmhafiz
期望的結果是什麼?平均數組? – matt