-2

我正在尝试在 ruby​​ 中返回数组数组的最大值

对于一维数组,这有效

arr = [99, 3, 14, 11, 1, 12]
position = arr.each_index.max

如何在 ruby​​ 中为多维数组实现相同的功能

arr = [[99, 3, 14], [11, 1, 12], [1.....]

我尝试使用 flatten 然后找到最大值的索引并尝试计算列和行但没有得到正确的结果并且感觉不对,有没有一种干净的方法可以用 ruby​​ 实现这一点?谢谢。

4

2 回答 2

1

这应该工作

arr.map(&:max).max

要查找索引,请尝试:

1.9.3p125 :018 > arr = [[99, 3, 14], [11, 1, 12], [1,10]]
 => [[99, 3, 14], [11, 1, 12], [1, 10]] 
1.9.3p125 :019 > arr.map{|sub| sub.each_with_index.max}.each_with_index.max_by{|sub_max| sub_max[0]}
 => [[99, 0], 0]
于 2012-12-16T22:53:37.033 回答
1

首先你得到最大值:

m = arr.flatten.max
#=> 99

那么听起来你要么想要包含 m 的数组的索引:

arr.index{|x| x.include? m}
#=> 0

或者那个索引加上 m 在那个数组中的索引

[i = arr.index{|x| x.include? m}, arr[i].index(m)]
#=> [0, 0]
于 2012-12-17T01:03:21.353 回答