How do I find the intersection of two lists including duplicates in mathematica?
So, If I have this:
list1 = {1, 1, 3, 4, 5, 6, 6, 6, 7, 7, 10, 11, 11};
list2 = {1, 1, 4, 5, 5, 6, 6, 7, 7, 8, 11, 11, 13, 14};
I'd want it to return this:
IntersectionIncludingDuplicates[list1, list2] = {1, 1, 4, 5, 6, 6, 7, 7, 11, 11}
Thanks for any and all help!
Here's one way:
Catenate@KeyValueMap[ConstantArray]@
MapThread[Min, KeyIntersection[Counts /@ {list1, list2}]]
Breaking it down:
Counts
)KeyIntersection
)MapThread
, Min
) and replicate the given element that many times (ConstantArray
)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With