I have an array which contains an arrays of Double
, like in the screenshot:
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.
Use the reduce(_:_:) method to produce a single value from the elements of an entire sequence. For example, you can use this method on an array of numbers to find their sum or product.
The compactMap(_:) function automatically removes nil elements from the returned array, after calling map(_:) on it. As such, it's return type is non-optional. In the above code, the type of result is [Int].
The map() Function in Swift. In Swift, you can use the built-in map() function to modify each element in a collection. The map() function loops through the collection, applying a function for each element. The map() function always returns an array where the transformed values are.
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
let sum = lists.reduce(0) { $0 + $1.reduce(1, combine: *) }
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 }
With the extension defined above you can also write
let sum = lists.map { $0.product }.reduce(0, combine:+)
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(*>)+>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With