Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get max and sum of 2nd column of array in ruby

Tags:

arrays

ruby

max

sum

for an array like

s = [[1,2],[4,6],[2,7]]

How i can select max and sum of 2nd column in each row in one statement

max= 7
sum= 15

I know, that

sum = 0
max = 0
s.each{ |a,b| sum+=b;if max<b then max = b end }

would work.

like image 415
NewMrd Avatar asked Jan 18 '26 16:01

NewMrd


2 Answers

The transpose method is nice for accessing "columns":

s = [[1,2],[4,6],[2,7]]
col = s.transpose[1]
p col.max #=> 7
p col.inject(:+) #=> 15
like image 168
steenslag Avatar answered Jan 20 '26 06:01

steenslag


second_elements = s.map { |el| el[1] }
sum = second_elements.inject{|sum,x| sum + x }
max = second_elements.max

To be more clear: inject{|sum,x| sum + x } returns nil if array is empty, so if you want to get 0 for empty array then use inject(0, :+)

like image 45
railscard Avatar answered Jan 20 '26 06:01

railscard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!