I have an array that should contain the same value throughout and if there are mismatches, I want to pull the index of those mismatches.
Example:
[1,1,1,1,3,1,1,1,2,1,1,1]
Output:
[4, 8]
What's the best way to accomplish this in Ruby/Rails?
You can get the most common element via tally
and max_by
:
arr = [1, 1, 1, 1, 3, 1, 1, 1, 2, 1, 1, 1]
most_common = arr.tally.max_by(&:last).first
#=> 1
tally
returns a hash containing the number of occurrences for each element ({1=>10, 3=>1, 2=>1}
), max_by(&:last)
returns the pair with the most occurrences and first
returns that element's value. (assuming there's always one most common element)
To get the indices, you can then utilize filter_map
:
arr.each_with_index.filter_map { |e, i| i if e != most_common }
#=> [4, 8]
each_with_index
yields each element with its corresponding index. filter_map
selects the truthy results from the block which returns the element's index if the element isn't equal to 1
. (and nil
otherwise, which gets discarded)