Enterprise Datacenter Management Voodoo
Posts tagged Arrays
Ruby on Rails intersections of multiple arrays
Feb 19th
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:
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.