finding the intersection in Ruby of 2 arrays is quite easy. If a is an array and b is an array then c can be the intersection as follows:

c = a & b

Similarly the union of the arrays can be found as follows:

c = a | b

The problem I had was finding the intersection of multiple arrays. So how to do it?

I did it as follows:

1. First find the union of all arrays.

2. Then take the intersection of the big union with each of the individual parts.

This sounds vaguely familiar to me as perhaps it was something I did in my computer science class at one point.

Anyway, here is the function:

1 2 3 4 5 6 7 8 9 10 11 12 |
def intersect(array_of_arrays) ar = [] # first find all the commons, then do intersection on it. array_of_arrays.each { |a| ar = a| ar } # now take the intersection of each array with the union of them all array_of_arrays.each { |a| ar = a & ar } ar end |

Anyway, if there’s some better way to do it, I’d love to know.

Comments are closed.