# every set intersection for every set in a family with another family of sets

I want to find for each list within a list of lists what intersections occur when taking set intersection for each list in another list of lists.

Hopefully that makes sense.

I have tried

Outer[Intersection[#1, #2] &, p1, p2]
MapThread[Intersection, {p1, p2}] (* This works but only when p1 and p2 are same length *)


where p1 = {{1, 2, 6}, {1, 2, 4, 6}, {1, 2, 3, 5, 6}} and p2= {{3, 5, 6}} But no such luck. The output should show that 6 is the only number in common between the list in p2 and each list in p1. If p2 contains another list, then the comparision function should perform the same check as with the 1st list in p2 but only care about the intersections that happen between this 2nd list and all the lists in p1.

I also should mention that when no intersections occur between list i in p1 with list j in p2 then something need to denote this (like {})

Ideally I want and output like result = {{{6},{6},{6}},{*results for 2nd element in p2*}} etc.

• Why is the third element of the desired result not {3,5,6}? – Daniel Lichtblau Apr 15 '20 at 21:43

From mobile, so not tested

Intersection@@#& /@ Tuples[{p1, p2}]


Update. Another solution, which preserves the inner/outer structure:

Table[Intersection[l1, l2], {l1, p1}, {l2, p2}]

• Nice. yes this returns same as mine. But I'm realizing that I need to organize the intersections into subcollections when comparing against a fixed list within the list of lists. (think each set of intersections corresponds to the index of the outside loop). – skyfire Apr 15 '20 at 21:35
• Table[Intersection[l1,l2], {l1, p1}, {l2, p2}] – Victor K. Apr 15 '20 at 21:40
• Table is a poor man’s map ;) – Victor K. Apr 15 '20 at 21:47
• perfect. I updated mine as well (the old fashioned way). Do you know how I can print this into a table to see the results a bit easier? (giving you the answer either way). – skyfire Apr 15 '20 at 21:47
• You should be able to just write Intersection@@@Tuples[{p1, p2}] for the first example – Lukas Lang Apr 16 '20 at 6:50
Outer[Intersection, p1, p2, 1]


{{{6}}, {{6}}, {{3, 5, 6}}}

• can't believe I only needed to add ,1] Welp won't be getting back those hours. – skyfire Apr 16 '20 at 0:53
• Don't fret too much about that. Consider it a rite of passage. :) – Suba Thomas Apr 16 '20 at 12:48

Here is the naive way (hoping for a more idiomatic, functional soln from someone).

p1 = {{1, 2, 6}, {1, 2, 4, 6}, {1, 2, 3, 5, 6}};
p2 = {{3, 5, 6}};
list = {}
Do[
AppendTo[list, {}]
Do[

If[IntersectingQ[p1[[x]], p2[[y]]],
Intersection[p1[[x]], p2[[y]]] // AppendTo[list[[y]], #] &,
Nothing]

, {x, 1, Length[p1]}]
, {y, 1, Length[p2]}]
list
$$$$
`