Ruby - 从数组中选择多个最大值及其索引

Ruby - pick multiple max values from an array with their index

说我有一个 数组 = [22, 55, 55, 16] 我想从数组中选出最大值及其索引。

只需使用 max 查找最大值,使用 index/rindexselect 查找索引取决于您需要哪种索引

array = [22, 55, 55, 16] 
max_val = array.max # 55
first_indedx = array.index(max_val) # 1 - first index
index = array.rindex(max_val) # 2 - last index
array.each_index.select{|i| array[i] == max_val} # [1, 2] - all indexes

您可以在此处找到有关方法的更多详细信息:https://ruby-doc.org/core-2.7.0/Array.html

你可以这样做:

$ irb
irb(main):001:0> i = [22, 55, 55, 16]
irb(main):003:0> i.each_with_index { |n, index| puts "#{n}:#{index}" if n == i.max }

55:1
55:2

Enumerable, there are the aptly named methods Enumerable#max and Enumerable#max_by.

的最大值

这是一个使用 Enumerable#max(或更准确地说,它的重载 Array#max)在 array:

中查找最大值的示例
array.max
#=> 55

如果您想要多个值,可以将 Integer 传递给 max,它会告诉 Ruby 您想要多少个值:

array.max
#=> 55

array.max(1)
#=> [55]

array.max(2)
#=> [55, 55]

array.max(3)
#=> [55, 55, 22]

array.max(4)
#=> [55, 55, 22, 16]

array.max(5)
#=> [55, 55, 22, 16]

所以,现在我们知道如何获得任意数量的最大值。我们现在唯一缺少的是索引。

所以,我们要做的第一件事就是将每个值与其索引配对:

array.each_with_index
#=> #<Enumerator: ...>

Enumerable#each_with_index returns an Enumerator, which pairs every element with its index. We can take a peek 看起来像什么:

enum = array.each_with_index
#=> #<Enumerator: ...>

enum.peek
#=> [22, 0]

或者,我们可以查看整个 Enumerator,使用 Enumerable#to_a method to convert it to an Array:

array.each_with_index.to_a
#=> [[22, 0], [55, 1], [55, 2], [16, 3]]

Arrays 是按字典顺序排列的,因此,Enumerable#max 会认为 [55, 2] 大于 [55, 1]:

array.each_with_index.max
#=> [55, 2]

array.each_with_index.max(1)
#=> [[55, 2]]

array.each_with_index.max(2)
#=> [[55, 2], [55, 1]]

array.each_with_index.max(3)
#=> [[55, 2], [55, 1], [22, 0]]

array.each_with_index.max(4)
#=> [[55, 2], [55, 1], [22, 0], [16, 3]]

array.each_with_index.max(5)
#=> [[55, 2], [55, 1], [22, 0], [16, 3]]

如果您同意 array 末尾的相等值,那么我们就完成了!

如果想在确定最大元素时忽略索引,我们可以使用Enumerable#max_by方法,它允许我们通过自己的标准来确定最大值。我们可以使用 Array#first 方法简单地告诉 Enumerable#max_by 只使用第一个元素:

array.each_with_index.max_by(&:first)
#=> [55, 1]

array.each_with_index.max_by(1, &:first)
#=> [[55, 1]]

array.each_with_index.max_by(2, &:first)
#=> [[55, 2], [55, 1]]

array.each_with_index.max_by(3, &:first)
#=> [[55, 2], [55, 1], [22, 0]]

array.each_with_index.max_by(4, &:first)
#=> [[55, 2], [55, 1], [22, 0], [16, 3]]

array.each_with_index.max_by(5, &:first)
#=> [[55, 2], [55, 1], [22, 0], [16, 3]]

给你!最大 n 个数字及其索引。