ios - Using nested reduce in Swift -


i have array contains arrays of double, in screenshot:

enter image description here

my goal sum of multiplication of double elements of each array. means, want multiply elements of each array then, in case, have 3 values sum of them.

i want use reduce, flatmap ? or elegant solution.

what have tried ?

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

but work when know size of arrays contains doubles.

given these values

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

let's take @ several possible approaches

solution #1

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

solution #2

if define extension

extension sequencetype generator.element == double {     var product : double { return reduce(1.0, combine: *) } } 

then can write

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

solution #3

with extension defined above can write

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

solution #4

if define these 2 postfix operators

postfix operator +>{} postfix func +>(values:[double]) -> double {     return values.reduce(0, combine: +) }  postfix operator *>{} postfix func *>(values:[double]) -> double {     return values.reduce(1, combine: *) } 

we can write

lists.map(*>)+> 

Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -