mylescc
mylescc

Reputation: 6859

Finding the common value in N number of arrays

I have n number of arrays and I want to work out if there is a common value in these arrays. If I knew the number of arrays I could do something like:

a = [1,2,3]
b = [2,4,5]
c = [2,6,7]

x = a & b & c

x == [2]

However, this isn't possible if you don't know the number of arrays. So far I've come up with this:

array_of_integers = [[1,2,3],[2,4,5]....]
values = []
array_of_integers.each_with_index do |array, index|
  values = if index.zero?
          array
        else
          values & array
        end
end
# `values` will be an array of common values

However, this doesn't seem very efficient. Is there a better way?

Upvotes: 3

Views: 98

Answers (1)

Igor Drozdov
Igor Drozdov

Reputation: 15045

However, this isn't possible if you don't know the number of arrays.

Actually, Enumerable#reduce can help with it:

[[1,2,3], [2,4,5], [2,6,7]].reduce(&:&) # => [2]

&:& looks interesting, but it's just:

[[1,2,3], [2,4,5], [2,6,7]].reduce { |memo, el| memo & el } # => [2]

Or it's also possible to do it as @Jagdeep suggested:

[[1,2,3], [2,4,5], [2,6,7]].reduce(:&) # => [2]

Upvotes: 10

Related Questions