英文:
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]]
我试图寻找一种简洁但易读的方法来实现以下目标:
- 比较并找到嵌套数组中索引位置[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:
- 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.
- 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]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论