Function Repository Resource:

IntersectionWithDuplicates

Source Notebook

Find elements common to multiple lists, including duplicates

Contributed by: Lou D'Andria

ResourceFunction["IntersectionWithDuplicates"][list1,list2,]

gives a sorted list of the elements common to all the listi, including duplicates.

Details

An element will appear in the resulting list n times if it appears n times in each of the listi.

Examples

Basic Examples (2) 

Find elements common to the given lists, with duplicates in the result if there are duplicates in all the lists:

In[1]:=
ResourceFunction[
 "IntersectionWithDuplicates"][{1, 2, 3, 1, 2, 3}, {1, 3, 1}]
Out[1]=

More than two lists can be given:

In[2]:=
ResourceFunction[
 "IntersectionWithDuplicates"][{a, a, b, b, c, c}, {a, b, b, b, c, c}, {b, b, b, b, b, b}]
Out[2]=

Applications (1) 

Find all prime factors common to two numbers:

In[3]:=
ResourceFunction["IntersectionWithDuplicates"][
 Splice @* Table @@@ FactorInteger[60],
 Splice @* Table @@@ FactorInteger[84]]
Out[3]=

Properties and Relations (2) 

IntersectionWithDuplicates returns all the same elements as Intersection, but possibly with different multiplicities:

In[4]:=
Intersection[Characters["WolframResearch"], Characters["Mathematica"], Characters["Champaign"]]
Out[4]=
In[5]:=
ResourceFunction["IntersectionWithDuplicates"][
 Characters["WolframResearch"], Characters["Mathematica"], Characters["Champaign"]]
Out[5]=

If there is no intersection, the result is {}:

In[6]:=
ResourceFunction["IntersectionWithDuplicates"][{a, b, c}, {d, e, f}]
Out[6]=

Publisher

Lou D'Andria

Version History

  • 1.0.0 – 08 August 2022

Related Resources

License Information