Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return the intersection of two lists including duplicates in mathematica?

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!

like image 338
Joseph Eck Avatar asked Sep 16 '25 12:09

Joseph Eck


1 Answers

Here's one way:

Catenate@KeyValueMap[ConstantArray]@
  MapThread[Min, KeyIntersection[Counts /@ {list1, list2}]]

Breaking it down:

  • Count how many times each element occurs in each list (Counts)
  • Retain only those elements which occur in both (KeyIntersection)
  • Take the smaller number of occurrences (MapThread, Min) and replicate the given element that many times (ConstantArray)
like image 116
Szabolcs Avatar answered Sep 18 '25 09:09

Szabolcs