返回Ruby中整数的2d数组中的最大数的索引
我试图返回ruby中数组数组的最大值 对于1d阵列,这是可行的返回Ruby中整数的2d数组中的最大数的索引,ruby,multidimensional-array,Ruby,Multidimensional Array,我试图返回ruby中数组数组的最大值 对于1d阵列,这是可行的 arr = [99, 3, 14, 11, 1, 12] position = arr.each_index.max 如何在ruby中实现多维数组的相同功能 arr = [[99, 3, 14], [11, 1, 12], [1.....] 我尝试过使用flatte,然后找到max的索引,并尝试计算出列和行,但没有得到正确的结果,而且感觉是错误的,有没有一种干净的方法用ruby来实现这一点?谢谢。这应该行得通 arr.map(&
arr = [99, 3, 14, 11, 1, 12]
position = arr.each_index.max
如何在ruby中实现多维数组的相同功能
arr = [[99, 3, 14], [11, 1, 12], [1.....]
我尝试过使用flatte,然后找到max的索引,并尝试计算出列和行,但没有得到正确的结果,而且感觉是错误的,有没有一种干净的方法用ruby来实现这一点?谢谢。这应该行得通
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]
首先获得最大值:
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]
2d数组需要两个索引吗?
arr.each_index.max
返回最大索引,而不是max元素的索引。这与arr.length-1
相同,它返回最大值,而不是最大值的索引(问题标题的典型情况与文本不同)。@steenslag但是,问题的第一行是我正在尝试返回ruby中数组的最大值。谢谢@pguardario这是有效的,如果问题不够详细,我会在我有能力的时候标记