Function Repository Resource:

MultisetComplement

Source Notebook

Perform the complement operation on multisets

Contributed by: Robert B. Nachbar (Wolfram Solutions)

ResourceFunction["MultisetComplement"][listall,list1,list2,]

gives the elements in listall that are in excess of those in all the listi.

ResourceFunction["MultisetComplement"][assocall,assoc1,assoc2,]

gives an Association where the keys are the union of the keys in the associations assocall and associ, and the values are the greater of the difference of the values in assocall and the sum of the values in the associ and 0.

Details and Options

The list returned by ResourceFunction["MultisetComplement"] is sorted into standard order.
If the listi are considered as multisets, ResourceFunction["MultisetComplement"] gives their complement.
The listi must have the same head, but it need not be List.
The values of associ must be counts—that is, non-negative Integer values.

Examples

Basic Examples (2) 

Find which elements in the first list are not in any of the subsequent lists:

In[1]:=
ResourceFunction[
 "MultisetComplement"][{a, a, a, b, b, c}, {a, c, c}, {b, d, d}]
Out[1]=

Multisets as Association of counts:

In[2]:=
ResourceFunction[
 "MultisetComplement"][<|"a" -> 3, "b" -> 1, "c" -> 2, "d" -> 1|>,
 <|"a" -> 2, "b" -> 2, "c" -> 2, "e" -> 1|>,
 <|"a" -> 1, "b" -> 2, "c" -> 2, "e" -> 2|>]
Out[2]=

Scope (1) 

MultisetComplement works with any head, not just List:

In[3]:=
ResourceFunction["MultisetComplement"][f[a, a, a, b, c, c], f[c, b], f[b, b, a]]
Out[3]=

Properties and Relations (1) 

Compare to Complement:

In[4]:=
ResourceFunction[
 "MultisetComplement"][{a, a, a, b, b, c}, {a, c, c}, {b, d, d}]
Out[4]=
In[5]:=
Complement[{a, a, a, b, b, c}, {a, c, c}, {b, d, d}]
Out[5]=

Publisher

Robert Nachbar

Requirements

Wolfram Language 11.3 (March 2018) or above

Version History

  • 1.0.0 – 19 February 2019

Related Resources

License Information