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

时间:2014-11-21 15:26:09

标签: ruby arrays

我有一个这样的数组:

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]

有没有人有更多像红宝石般的方法来做这个?

4 个答案:

答案 0 :(得分:3)

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

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 ]

答案 1 :(得分:3)

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] 

答案 2 :(得分:3)

试试这个:

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

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

注意:答案来自Find indices of elements that match a given condition

答案 3 :(得分:0)

如果你想避免两次传递(即一次获得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