Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List the maximum or minimum of the elements at each position of two arrays

Tags:

arrays

ruby

Given two Fixnum arrays of equal length, is there a Ruby way to produce an array holding the maximum or minimum values at each index?

For example:

a1 = [ 10, 30 ]
a2 = [ 5,  35 ]

The min function would return 5 from the first column and 30 from the second column, giving [5, 30]. Likewise, the max function would return 10 from the first column and 35 from the second column, giving [10, 35].

like image 889
TX T Avatar asked Dec 05 '25 03:12

TX T


1 Answers

You can construct arrays of the elements at common positions (that is, transpose a row-wise 2D array into a column-wise 2D array), then map the min or max (or whatever else) values out of each column:

[a1, a2].transpose.map &:min    #  => [5, 30]
[a1, a2].transpose.map &:max    #  => [10, 35]
like image 85
Chris Heald Avatar answered Dec 06 '25 17:12

Chris Heald