2017-01-23 143 views
2

数组我有一个数组:[1, 2, 3, 4, 5, 6...100]迭代的范围

我找了5遍历数组,具体如下:

在第一个5个号码的阵列,并获得平均,移动在接下来的5个数字,并获得平均值,等等。

我已经尝试了很多方法,如Dequeue和for循环,但一直没有能够得到所需的结果。

+0

使用这并计算出平均值https://gist.github.com/ericdke/fa262bdece59ff786fcb – xmhafiz

+1

期望的结果是什么?平均数组? – matt

回答

0

您需要使用一个进展循环迭代每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] 
0

尝试这种情况:

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]