MicFin
MicFin

Reputation: 2501

Find out if a specified number of array elements match

What's a simple way to write a method for checking if a certain number of array elements match. For example

["dog", "cat", "dog", "dog"].has_matching(3) 
# true

and

["dog", "cat", "dog", "cat"].has_matching(3)
# false

Ideally the class of the objects being compared would not matter.

Upvotes: 1

Views: 53

Answers (1)

Cristian Lupascu
Cristian Lupascu

Reputation: 40516

You could add a method to Array:

class Array
  def check_if_minimum_duplicates(min_dup)
    group_by{|el| el }.any?{|k, v| v.count >= min_dup }
  end
end

and use it like this:

irb(main):006:0> puts ["dog", "cat", "dog", "dog"].check_if_minimum_duplicates(3)
true
=> nil
irb(main):007:0> puts ["dog", "cat", "dog", "cat"].check_if_minimum_duplicates(4)
false
=> nil

Upvotes: 3

Related Questions