I would like an intersection function on lists like Intersection that also stores the coordinates of the intersections. For instance for {a,b,c}
and {b,c,e}
would give something like {{b,2,1},{c,3,2}}
.
If more elements match preferably it saves all of the positions. So {a,b,c,a}
and {d,c,a,c}
would give something like {a,{1,4},3},{c,3,{2,4}}}
.
Can this be done easily?
(Only a comparison of two lists is needed for the present purpose. But a more general function that can be applied to any number of lists might be nice to have ready in the future too.)
Answer
I'll take "... give something like..." to mean we can take some liberties with output format.
myFn=Merge[KeyIntersection[PositionIndex /@ {##}], Identity]&;
will produce an association with the desired information, works with any number of lists.
l1 = {a, b, c, a};
l2 = {d, c, a, c};
l3 = {z, d, d, a, c, k};
myFn[l1,l2,l3]
<|a -> {{1, 4}, {3}, {4}}, c -> {{3}, {2, 4}, {5}}|>
Comments
Post a Comment