Using nested shorthand in Swift

I have an array containing arrays Double, as in the screenshot:

enter image description here

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

I want to use reduce, flatMap? or any elegant solution.

What have i tried?

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

but this only works when I know the size of arrays containing doubles.

+4
source share
3 answers

Given these values

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

consider several possible approaches

Decision No. 1

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

Decision number 2

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

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

№ 3

, ,

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

№ 4

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

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

lists.map(*>)+>
+7

:

let totalCombinations: [[Double]] = [
    [2.4,1.45,3.35],
    [2.4,1.45,1.42],
    [2.4,3.35,1.42],
    [1.45,3.35,1.42],
]

let result = totalCombinations.reduce(0.0) {$0 + $1.reduce(1.0) {$0 * $1} }

print(result) //->34.91405

, "" .

+2

Perhaps this is what you are looking for

let a = [1.0, 2.0, 3.0]
let b = [4.0, 5.0, 6.0]
let c = [7.0, 8.0, 9.0, 10.0]

let d = [a, b, c]

let sum = d.reduce(0.0) { $0 + $1.reduce(1.0) {$0 * $1}}
print(sum) // prints 5166.0
+2
source

Source: https://habr.com/ru/post/1649387/


All Articles