2017-01-27 8 views
0

Swift 3では、Intの配列内の5つの要素の合計をどのように計算できますか?Swift iOSのInteger配列の5要素ごとの合計を計算する

例えば、我々は持っている配列[1,2,3,4,5,6,7,8,9,0,12,23]

1+2+3+4+5 = 15 
    6+7+8+9+0 = 30 
    12+23+0+0+0 = 35 

このような結果何か[15ここで、30,35]

+5

をあなたが試みられてきたものをご提示ください。 – Paulw11

+0

を見てください: http://stackoverflow.com/questions/24795130/finding-sum-of-elements-in-swift-array –

+1

http://stackoverflow.com/questions/27984914/swiftを見てください各スライスに相当する。 –

答えて

2

はplaygroudの私のソリューションです:

//: Playground - noun: a place where people can play 

import UIKit 

var arr = [1,1,1,1,1,2,2,2,2,2,3,3,3,3,3] 

let chunkSize = 5 
let chunks = stride(from: 0, to: arr.count, by: chunkSize).map { 
    Array(arr[$0..<min($0 + chunkSize, arr.count)]) 
} 

print(chunks) 

var summ = chunks.map { $0.reduce(0, {$0 + $1}) } 

print(summ) 

OUTPUT:

[1、1、1、1、1]、[2、2、2、2、2]、[3、3、3、3、3]

[5、10、15]

を見てみましょう: Finding sum of elements in Swift array

+0

関数型プログラミングをうまく利用できます! (投票された) –

関連する問題