Abdirizak Obsiye
Abdirizak Obsiye

Reputation: 285

How to find the sum of each row for a multi-dimensional array

I would like to find the sum of each row of a multidimensional array, and have the sums an array, e.g., for [[1,2,3],[1,1,1]], I would like to get [6,3].

I tried the following:

arr = [[1,2,3],[3,2,1],[2,1,3]]
print arr.each{|row| row.each{|column| puts column}}

Results:

1
2
3
3
2
1
2
1
3
[[1, 2, 3], [3, 2, 1], [2, 1, 3]]

I am struggling with it. I still don't fully understand each iterators. Any help would be appreciated.

Upvotes: 0

Views: 579

Answers (4)

Mark Thomas
Mark Thomas

Reputation: 37507

"How to find the sum of each row"

arr = [[1,2,3], [1,1,1]]

print arr.each{|row| <-- here you have each row

So now row contains [1,2,3] initially. As others have mentioned, you can apply a sum here. (You don't need the leading print).

arr.each{|row| puts row.sum}

Result:

6
3

But a better way to do it is with map. As I told a Ruby newbie many years ago, think of map when you want to change every element to something else, in other words a "1:1 mapping" of input to output. In this case the output is row.sum:

sums = arr.map{|row| row.sum}

Result:

[6, 3]

Upvotes: 0

dfherr
dfherr

Reputation: 1642

[[1,2,3],[1,1,1]].map { |a| a.inject(0, :+) } # => [6 , 3]
  1. map changes each element to the return value of this elements block
  2. get the sum for each array with inject(:+)
  3. use inject(0, :+) to set 0 instead of the first element as the start value (handles empty inner array)

see:

Upvotes: 1

sawa
sawa

Reputation: 168081

[[1,2,3],[1,1,1]].map{|a| a.inject(:+)} # => [6, 3]

If there is a possibility that any of the sub-array can be empty, then you need to add the initial 0, as Ursus pointed out.

[[1,2,3],[1,1,1]].map{|a| a.inject(0, :+)} # => [6, 3]

Upvotes: 3

Ursus
Ursus

Reputation: 30056

For ruby 2.4.0 or newer

a.map { |suba| suba.sum }

or simply

a.map(&:sum)

for ruby prior to 2.4.0

a.map { |suba| suba.inject(0, :+) }

Upvotes: 4

Related Questions