Reputation: 31645
Let's say that I have the following 2d array:
let my2dArray = [[01, 02, 03, 04],
[05, 06, 07, 08],
[09, 10, 11, 12],
[13, 14, 15, 16]]
What is the easiest way to get the summation of all elements in my2dArray
?
Assuming that the output should be:
01 + 02 + 03 + 04 + 05 + 06 + 07 + 08 + 09 + 10 + 11 + 12 + 13 + 14 + 15 + 16 = 136
Upvotes: 3
Views: 1642
Reputation: 31645
I came up with:
Non-Swifty Solution (Works as it should, but not "Swifty"):
var summation = 0
for i in 0..<my2dArray.count {
for j in 0..<my2dArray[i].count {
summation += my2dArray[i][j]
}
}
print(summation) // 136
Swifty Solution (The easiest way):
let summation = my2dArray.map { $0.reduce(0, +) }.reduce(0, +)
print(summation) // 136
Any other -more efficient- "Swifty" solution would be really appreciated.
Upvotes: 1
Reputation: 154603
One way is to use joined()
to flatten the array and then reduce
to sum it:
let my2dArray = [[01, 02, 03, 04],
[05, 06, 07, 08],
[09, 10, 11, 12],
[13, 14, 15, 16]]
let result = my2dArray.joined().reduce(0, +)
print(result) // 136
Note that my2dArray.joined()
doesn't create another array, but instead it creates a FlattenBidirectionalCollection<Array<Array<Int>>>
which allows sequential access to the items, both forwards and backwards, but it does not allocate new storage. You can of course do Array(my2dArray.joined())
if you wish to see how it looks in array format.
Upvotes: 6
Reputation: 1198
Just a couple more ways to do this:
let my2darray = [[01, 02, 03, 04],
[05, 06, 07, 08],
[09, 10, 11, 12],
[13, 14, 15, 16]]
let doubleReduced = my2darray.reduce(0, {$1.reduce(0, +) + $0})
let dontForgetFlatmap = my2darray.flatMap{$0}.reduce(0,+)
Upvotes: 3