如何使用Ruby访问和比较这些嵌套数组的值?

huangapple go评论83阅读模式
英文:

How, with Ruby, can I access and compare these nested array values?

问题

我有这个嵌套数组:

[[1, 2, 3],
[1, 3, 6],
[1, 4, 12],
[1, 5, 5],
[1, 2, 3],
[1, 8, 7],
[2, 3, 3],
[2, 4, 9],
[2, 5, 2],
[2, 8, 4],
[3, 4, 6],
[3, 8, 1],
[5, 8, 2],
[2, 8, 4],
[7, 8, 9]]

我试图寻找一种简洁但易读的方法来实现以下目标:

  1. 比较并找到嵌套数组中索引位置[2](即每个嵌套数组的第三个元素)的最大值。
  2. 返回包含来自步骤1中找到的最大值的嵌套数组中索引[0]和[1]的相邻值。

我尝试过使用#max#max_by#group_by#with_index等各种方法,但现在我只需要一些比我更有能力的大脑和程序员的启发。

英文:

I have this nested array:

[[1, 2, 3],                                                                   
 [1, 3, 6],                                                                   
 [1, 4, 12],                                                                  
 [1, 5, 5],                                                                   
 [1, 2, 3],                                                                   
 [1, 8, 7],                                                                   
 [2, 3, 3],                                      
 [2, 4, 9],                                      
 [2, 5, 2],                                      
 [2, 8, 4],                                      
 [3, 4, 6],                                      
 [3, 8, 1],                                      
 [5, 8, 2],                                      
 [2, 8, 4],                                      
 [7, 8, 9]]

and I am trying to find a succinct but readable way of:

  1. comparing and finding the maximum value from those values in index position[2] (i.e. 3rd element in each nested array) within each of the nested arrays.
  2. Returning the neighbouring values at index[0] and [1] from the same nested array containing the maximum value from point 1.

I've unsuccessfully played around with various methods such as #max, #max_by, #group_by, #with_index but I'm now at the stage where I could just do with some enlightenment from a more capable brain and programmer then me.

答案1

得分: 6

查找具有最大值的嵌套数组的最后一个元素:

input = [[1, 2, 3], [1, 3, 6], [1, 4, 12], [1, 5, 5], [1, 2, 3], [1, 8, 7], [2, 3, 3], [2, 4, 9], [2, 5, 2], [2, 8, 4], [3, 4, 6], [3, 8, 1], [5, 8, 2], [2, 8, 4], [7, 8, 9]]
input.max_by(&:last)
# => [1, 4, 12]

并且仅返回其前两个值:

input.max_by(&:last).take(2)
# => [1, 4]
英文:

Finding the nested array with the max value on the last element:

input = [[1, 2, 3], [1, 3, 6], [1, 4, 12], [1, 5, 5], [1, 2, 3], [1, 8, 7], [2, 3, 3], [2, 4, 9], [2, 5, 2], [2, 8, 4], [3, 4, 6], [3, 8, 1], [5, 8, 2], [2, 8, 4], [7, 8, 9]]
input.max_by(&:last)
#=> [1, 4, 12]

And to only return its first two values:

input.max_by(&:last).take(2)
#=> [1, 4]

huangapple
  • 本文由 发表于 2023年3月7日 22:35:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/75663337.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定