繁体   English   中英

查找数组中最大元素的所有索引

[英]Find all indexes of maximum elements in array

我有这样一个数组:

vals = [1,2,10,5,10,5,9,10]

我需要数组中最大元素的索引(在上面的例子10 )。 所以在我的例子中,它应该吐出另一个数组:

[2, 4, 7]

但是,当我将#find_index与块一起使用时,我只能得到它匹配的第一个索引:

[12] pry(main)> vals.find_index { |i| i == vals.max }
=> 2

我可以通过这样做得到我想要的但看起来有点冗长:

[14] pry(main)> results = []
=> []
[15] pry(main)> vals.each_with_index do |elem, i|
[15] pry(main)*   results << i if elem == vals.max
[15] pry(main)* end
=> [1, 2, 10, 5, 10, 5, 9, 10]
[16] pry(main)> results
=> [2, 4, 7]

有没有人有任何想法更像红宝石的方式来做到这一点?

它有点乱,但你可以这样做:

vals = [ 1,2,10,5,10,5,9,10 ]
val_max = vals.max

result = vals.each_with_index.each_with_object([ ]) do |(v,i),a|
  a << i if (v == val_max)
end

# => [ 2, 4, 7 ]
vals = [1, 2, 10, 5, 10, 5, 9, 10]
max = vals.max

vals.map.with_index {|n, i| i if n == max }.compact
# => [2, 4, 7] 

尝试这个:

vals = [1, 2, 10, 5, 10, 5, 9, 10]
max_val = vals.max

vals.each_index.select{|i| vals[i] == max_val}

注意:答案来源于查找与给定条件匹配的元素的索引

如果你想避免两次传递(即一次获得max_val,然后再次遍历列表):

vals    = [ 1,2,10,5,10,5,9,10 ]
max_val = vals.first - 1
indices = []

vals.each_with_index do |n, idx|
  if n < max_val
    # Do nothing, but common case, so avoid second comparison
  elsif n == max_val
    indices << idx
  elsif n > max_val
    max_val = n
    indices = [ idx ]
  end
end

indices

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM