5

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.

0

3 Answers 3

8

Given these values

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

let's take a look at several possible approaches

Solution #1

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:+)

Solution #4

If we 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(*>)+>
Sign up to request clarification or add additional context in comments.

Comments

2

You can write something like this:

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

But I'm not sure it's "elegant" or not.

2 Comments

Not sure if considered more elegant in this case, but you can pass the * operator to reduce directly ($1.reduce(1, combine: *))
@Hamish, good point. But it's already included in appzYourLife's answer. So, I think I'm late.
2

Maybe this is what you're 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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.