Find a large basement array from a ruby ​​multidimensional array

I want to find the largest additional array from 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 auxiliary array to have the largest second element, as in the above example. I want it to 5be as a result, because the second element of the auxiliary array [5,100]is the largest that is 100. The output will be 5.

And if more than one element is maximal than I want it all.

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

The conclusion in this case will be [5,12]

Thanks in advance.

+4
4

Enumerable#max_by, , .

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

UPDATE:

, , .

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

, ,

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

-

array.max_by(&:last).first
+3

.

Arie largest:

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

Enumerable#map Array#compact :

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

...

Hash, , ...

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

:

hash.values.max
#=> 100

- :

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

:

hash.select { |k, v| v == hash.values.max }.keys
#=> [5, 12]
+1
source
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]
+1
source

Source: https://habr.com/ru/post/1531098/


All Articles