如何以稳定的顺序查找数组中max n个元素的索引

com*_*psy 0 ruby arrays

我有一个数字和一个数组:

n = 4
a = [0, 1, 2, 3, 3, 4]
Run Code Online (Sandbox Code Playgroud)

我想找到与元素大小相反的最大n元素对应的索引a,并且当元素大小相等时以稳定的顺序找到.预期的产出是:

[5, 3, 4, 2]
Run Code Online (Sandbox Code Playgroud)

这段代码:

a.each_with_index.max(n).map(&:last) 
# => [5, 4, 3, 2]
Run Code Online (Sandbox Code Playgroud)

给出正确的指数,但改变顺序.

Car*_*and 5

def max_with_order(arr, n)
   arr.each_with_index.max_by(n) { |x,i| [x,-i] }.map(&:last)
end
Run Code Online (Sandbox Code Playgroud)

例子

a = [0,1,2,3,3,4]

max_with_order(a, 1)  #=> [5]
max_with_order(a, 2)  #=> [5, 3]
max_with_order(a, 3)  #=> [5, 3, 4]
max_with_order(a, 4)  #=> [5, 3, 4, 2]
max_with_order(a, 5)  #=> [5, 3, 4, 2, 1]
max_with_order(a, 6)  #=> [5, 3, 4, 2, 1, 0]
Run Code Online (Sandbox Code Playgroud)

说明

对于n = 3步骤如下.

b = a.each_with_index
  #=> #<Enumerator: [0, 1, 2, 3, 3, 4]:each_with_index>
Run Code Online (Sandbox Code Playgroud)

我们可以转换b为数组来查看它将生成的(六个)值并传递给块.

b.to_a                
  #=> [[0, 0], [1, 1], [2, 2], [3, 3], [3, 4], [4, 5]]
Run Code Online (Sandbox Code Playgroud)

继续,

c = b.max_by(n) { |x,i| [x,-i] }
  #=> [[4, 5], [3, 3], [3, 4]]
c.map(&:last)
  #=> [5, 3, 4]
Run Code Online (Sandbox Code Playgroud)

请注意,元素arr不必是数字,只是可比较的.