Arun Kumar
Arun Kumar

Reputation: 31

How do I find intersection of 3 arrays, while ignoring empty arrays?

I have to find intersection elements of 3 integer arrays say a, b, c with a condition; if any of the array is null ( [] ), simply ignore the array and find intersection of the remaining arrays, and if all three are null, then return []. Thanks in advance.

ps:Ruby 1.9.3

Upvotes: 3

Views: 1076

Answers (3)

Boris Stitnicky
Boris Stitnicky

Reputation: 12578

One way to do it would be this:

[ a, b, c ].tap{ |a| a.delete( [] ) }.reduce( :& ) || []

Other options suggested in the discussion are:

[ a, b, c ].reject( &:empty? ).reduce( :& ) || []

and:

[ a, b, c ].select( &:any? ).reduce( :& ) || []

But in this last case, beware of non-empty arrays with explicit nil elements, such as [ nil ], cause they still fail #any? test.

Upvotes: 5

brentmc79
brentmc79

Reputation: 2541

There's probably a more concise means of doing this, but this should get you what you need.

def intersection(*arrays)
  # Reduce the list of arrays to only the ones with elements
  arrays = arrays.select(&:first)

  return [] if arrays.empty?

  # Grab the first array
  intersection = arrays.pop

  # Iterate over the arrays finding the intersection
  arrays.each do |array|
    intersection = intersection & array
  end

  # Return the resultant array
  intersection
end

UPDATE

I knew there was a method to apply an operator between all of the arrays elements, but for some reason I missed reduce when looking over the array docs. reduce is definitely the way to go:

arrays.reject(&:empty?).reduce(&:&)

Upvotes: 0

ChuckE
ChuckE

Reputation: 5688

[a, b, c].reject(&:blank?).reduce(:&)

Upvotes: 1

Related Questions