Find all indices of maximum elements in an array

I have an array like this:

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

      

I need the indices of the largest element in an array (in the above example 10

). So in my example, it should spit out another array:

[2, 4, 7]

However, when I use #find_index

with a block, I can only get the first index that it matches:

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

      

I can get what I want by doing this, but it looks somewhat verbose:

[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]

      

Does anyone have any ideas for a more ruby ​​way to do this?

+3


source to share


4 answers


Try the following:

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

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

      



Note: answer derrived from Find indices of elements that match a given condition

+3


source


It's a little messy, but you can do this:



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 ]

      

+3


source


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] 

      

+3


source


If you want to avoid two passes (for example, to get max_val, and then internet through the list again):

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

      

0


source







All Articles