Skip to main content
added 334 characters in body
Source Link
E. Chan-López
  • 31.3k
  • 3
  • 29
  • 50

Using DeleteCases and Union:

SetDifference[setsSetDifference[sets__?VectorQ, 
   Optional[opts : {__Automatic ?| VectorQ}"SortAndDistinct", opts___]Automatic]] := 
  Module[
    {setarray, sdiff, sdiffsorted},
    sdiffsetarray = {sets};
    sdiff = DeleteCases[First @ setssetarray, 
            Apply[Alternatives, Union @@ Rest[sets]]];Rest[setarray]]
    Piecewise    ];
    sdiffsorted = Union @ {sdiff;
    Switch[
         {sdiff, SameQ[opts  opts, Null]}Automatic,
            {Union @   sdiff, SameQ[opts"SortAndDistinct", 
 "SortAndDistinct"]}               sdiffsorted
        }]
   ];

   l1 = {b, e, d, a, b, c, d}; l2 = {b, c}; l3 = {a, f};

   SetDifference[SetDifference[l1, l2, l3]

   (*{l1e, d, d}*)

   SetDifference[l1, l2, l3}], "SortAndDistinct"]

   (*{d, e}*)

   SetDifference[{a, b, b, d, e}, {c}, {c, e}, {d}]

   (*{a, b, b}*)

   SetDifference[{l1a, l2b, l3b, d, e}, {c}, {c, e}, {d}, "SortAndDistinct"]

   (*{da, eb}*)

Using DeleteCases and Union:

SetDifference[sets : {__ ? VectorQ}, opts___] := Module[{sdiff},
    sdiff = 
    DeleteCases[First @ sets, 
     Apply[Alternatives, Union @@ Rest[sets]]];
    Piecewise @ {
            {sdiff, SameQ[opts, Null]},
            {Union @ sdiff, SameQ[opts, "SortAndDistinct"]}
        }
   ];

   l1 = {b, e, d, a, b, c, d}; l2 = {b, c}; l3 = {a, f};

   SetDifference[{l1, l2, l3}]

   (*{e, d, d}*)

   SetDifference[{l1, l2, l3}, "SortAndDistinct"]

   (*{d, e}*)

Using DeleteCases and Union:

SetDifference[sets__?VectorQ, 
   Optional[opts : Automatic | "SortAndDistinct", Automatic]] := 
  Module[
    {setarray, sdiff, sdiffsorted},
    setarray = {sets};
    sdiff = DeleteCases[First @ setarray,
            Apply[Alternatives, Union @@ Rest[setarray]]
        ];
    sdiffsorted = Union @ sdiff;
    Switch[
            opts, Automatic,
                sdiff, "SortAndDistinct", 
                sdiffsorted
        ]
   ];

   l1 = {b, e, d, a, b, c, d}; l2 = {b, c}; l3 = {a, f};

   SetDifference[l1, l2, l3]

   (*{e, d, d}*)

   SetDifference[l1, l2, l3, "SortAndDistinct"]

   (*{d, e}*)

   SetDifference[{a, b, b, d, e}, {c}, {c, e}, {d}]

   (*{a, b, b}*)

   SetDifference[{a, b, b, d, e}, {c}, {c, e}, {d}, "SortAndDistinct"]

   (*{a, b}*)
Source Link
E. Chan-López
  • 31.3k
  • 3
  • 29
  • 50

Using DeleteCases and Union:

SetDifference[sets : {__ ? VectorQ}, opts___] := Module[{sdiff},
    sdiff = 
    DeleteCases[First @ sets, 
     Apply[Alternatives, Union @@ Rest[sets]]];
    Piecewise @ {
            {sdiff, SameQ[opts, Null]},
            {Union @ sdiff, SameQ[opts, "SortAndDistinct"]}
        }
   ];

   l1 = {b, e, d, a, b, c, d}; l2 = {b, c}; l3 = {a, f};

   SetDifference[{l1, l2, l3}]

   (*{e, d, d}*)

   SetDifference[{l1, l2, l3}, "SortAndDistinct"]

   (*{d, e}*)