[英]How to find indices of max n elements in array in stable order
我有一个数字和一个数组:
n = 4
a = [0, 1, 2, 3, 3, 4]
我想以与元素大小相反的顺序找到与a
的最大n
元素相对应的索引,并且在元素大小相等时以稳定的顺序查找。 预期的输出是:
[5, 3, 4, 2]
这段代码:
a.each_with_index.max(n).map(&:last)
# => [5, 4, 3, 2]
给出正确的索引,但更改顺序。
码
def max_with_order(arr, n)
arr.each_with_index.max_by(n) { |x,i| [x,-i] }.map(&:last)
end
例子
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]
说明
对于n = 3
,步骤如下。
b = a.each_with_index
#=> #<Enumerator: [0, 1, 2, 3, 3, 4]:each_with_index>
我们可以将b
转换为数组,以查看它将生成并传递给块的(六个)值。
b.to_a
#=> [[0, 0], [1, 1], [2, 2], [3, 3], [3, 4], [4, 5]]
继续,
c = b.max_by(n) { |x,i| [x,-i] }
#=> [[4, 5], [3, 3], [3, 4]]
c.map(&:last)
#=> [5, 3, 4]
请注意, arr
的元素不必是数字,而只是可比较的。
您可以为max
提供一个块,以使确定更加具体,例如
a.each_with_index.max(n) do |a,b|
if a[0] == b[0] # the numbers are the same
b[1] <=> a[1] # compare the indexes in reverse
else
a[0] <=> b[0] # compare the numbers themselves
end
end.map(&:last)
#=> [5,3,4,2]
max
块期望可比的响应,例如-1,0,1,因此在这种情况下,我们只是说如果数字相同,则以相反的顺序比较索引,例如4 <=> 3 #=> -1
,-1表示值较小,因此将其放置在3之后
还要扩展@CarySwoveland的答案(我没想到我有点嫉妒),因为您只关心返回索引,所以可以在没有辅助map
情况下实现如下
a.each_index.max_by(n) { |x| [a[x],-x] }
#=> [5,3,4,2]
您在不更改顺序的情况下编写的@compsy,将是:
a = [0,1,2,3,3,4]
n = a.max
i = 0
a.each do |x|
break if x == n
i += 1
end
我使用变量i作为索引,当x (即beeing分析的值)等于n时,我们使用break停止每种方法,保留i的最后一个值对应于数组中最大值的位置。 请注意, i的值与数组中的自然位置不同,这是因为数组中的第一个元素为0而不是1。
我打破了每个,因为在找到值的位置之后,无需继续检查数组的所有其他值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.