iOSGeek iOSGeek - 4 months ago 16
iOS Question

Using nested reduce in Swift

I have an array which contains an arrays of double, like in the screenshot:

enter image description here

My goal is to get the sum of the multiplication of the double elements of each array. It means, I want to multiply all elements of each array then in my case I will have 3 values so I get the sum of them.

I want to use

reduce
,
flatMap
? or any elegant solution.

What I have tried ?

totalCombinations.reduce(0.0) { $0 + ($1[0]*$1[1]*$1[2]) }


but this work only when I know the size of the arrays that contains the doubles.

Answer

Solution #1

Just another way

let lists: [[Double]] = [[1.1, 2.2, 3.3], [4.4, 5.5, 6.6]]

let sum =  lists.reduce(0) { $0 + $1.reduce(1, combine: *) }

Solution #2

If you define this extension

extension SequenceType where Generator.Element == Double {
    var product : Double { return reduce(1.0, combine: *) }
}

then you can write

let sum = lists.reduce(0) { $0 + $1.product }

Solution #3

With the extension defined above you can also write

let sum = lists.map { $0.product }.reduce(0, combine:+)
Comments