简体   繁体   中英

Find largest sub array out of ruby multidimensional array

I want to find out the largest sub array out of a multidimensional array in ruby. I have a multidimensional array as follows :

array = [[1,20],[2,40],[5,100],[7,15],[9,22]]

I want the first element of the sub array which second element is largest like in the above example I want the 5 as an output because second element of sub array [5,100] is largest which is 100 . The output would be 5 .

And if more then one element are maximum than i want all these.

Ex: array = [[1,20],[2,40],[5,100],[7,15],[9,22],[12,100]]

The out put in this case would be [5,12]

Thanks in advance.

You can use the Enumerable#max_by method to select the max element, and then project that element to the result value.

array.max_by{|a| a[1]}[0]

UPDATE:

If you want all the elements with the maximum value, you can first get the max value from the array, and then filter the array with that value.

max_value = array.max_by{|a| a[1]}[1]
results = array.select{|a| a[1] == max_value}.map(&:first)

You may use one line expression, but I think that's less readable

array.group_by{|a| a[1]}.max_by{|k,v| k}[1].map(&:first)

尝试类似的东西

array.max_by(&:last).first

Following updated question.

You could use Arie's answer to compute largest :

largest = array.max_by { |a| a[1] }[1] #=> 100

Then combine Enumerable#map with Array#compact to get:

array.map { |a| a.first if a[1] == largest}.compact #=> [5, 12]

Better still...

Use a Hash , as mentioned in my answer to your earlier question ...

hash
#=> {1=>20, 2=>40, 5=>100, 7=>15, 9=>22, 12=>100}

Largest value:

hash.values.max
#=> 100

Key-value pairs with the largest value:

hash.select { |k, v| v == hash.values.max }
#=> {5=>100, 12=>100}

Keys with the largest value:

hash.select { |k, v| v == hash.values.max }.keys
#=> [5, 12]
a =  [[1,20],[2,40],[5,100],[7,15],[9,22],[12,100]]

max = a.map(&:last).max

a.select{|x|x.last==max}.map(&:first) #=> [5, 12]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM