Message Boards Message Boards

Delete cases using a "Complement" that accounts for multiplicities?

GROUPS:

Hi, I have cats, fish and dogs.

In[173]:= animals = {cat, dog , fish, dog, cat}
Out[173]= {cat, dog, fish, dog, cat}

I want to take out the fish.

In[174]:= Complement[animals, {fish}]
Out[174]= {cat, dog}

Unfortunately Mathamatica killed one of my cat and one of my dog. I want a result that looks like:

Out[173]= {cat, dog, dog, cat}

or if Mathematica really wants to sort it, then:

Out[173]= {cat, cat, dog, dog}

How can I do it and make it fast?

Thanks ahead, János

P.S. The documentation says only that the result is sorted.

POSTED BY: smile sung
Answer
1 month ago

This functionality is not (yet) built-in. Complement does not take into account any multiplicities. You can make your own:

ClearAll[Complement2]
Complement2[eall_List, e1_List] := Module[{out, pos},
  out = eall;
  Do[
   pos = FirstPosition[out, e];
   If[! MissingQ[pos],
    out = Delete[out, pos];
    ]
   ,
   {e, e1}
   ];
  out
  ]

And try it out:

Complement2[{cat, dog, fish, dog, cat}, {fish}]
POSTED BY: Sander Huisman
Answer
1 month ago

There is also DeleteCases...

POSTED BY: Daniel Lichtblau
Answer
1 month ago

Group Abstract Group Abstract