3

I have a set:

$$A=\{\{1,2,3\},\{1,3,2\},\{2,1,3\},\{2,3,1\},\{3,1,2\},\{3,2,1\}\}$$

I want to drop elements found in sets B and C from A.

$$B=\{\{1,3,2\},\{2,1,3\}\}$$ $$C=\{\{3,1,2\},\{3,2,1\}\}$$ How can I do this?


My attempts:

A = {{1, 2, 3}, {1, 3, 2}, {2, 1, 3}, {2, 3, 1}, {3, 1, 2}, {3, 2, 1}}
B = {{1, 3, 2}, {2, 1, 3}}
C = {{3, 1, 2}, {3, 2, 1}}
DeleteCases[A, B]

It does not give the desired result I had to write it like this

DeleteCases[A, {1, 3, 2}]

I also tried to do it iteratively but it did not work.

Syed
  • 52,495
  • 4
  • 30
  • 85

3 Answers3

6

This is the exact use case for Complement:

a = {{1, 2, 3}, {1, 3, 2}, {2, 1, 3}, {2, 3, 1}, {3, 1, 2}, {3, 2, 1}};
b = {{1, 3, 2}, {2, 1, 3}};
c = {{3, 1, 2}, {3, 2, 1}};

Complement[a, b, c]

(* Out: {{1, 2, 3}, {2, 3, 1}} *)

As an aside, do not use variable names that start with capital letters because those have customarily been reserved for built in functions. In particular, avoid using single-letter uppercase variable names like A, B, C (used as a constant in equation solving), I (the imaginary unit), E (the base of natural logarithms), K, and more: many have built-in meaning which can lead to odd behavior and hard-to-trace bugs.

MarcoB
  • 67,153
  • 18
  • 91
  • 189
5

Using DeleteCases:

This will delete any x such that x is a member of either b or c.

DeleteCases[a, x_ /; MemberQ[b, x] || MemberQ[c, x]]

Using Complement:

Complement[Complement[a, b], c]

or better still:

Fold[Complement, a, {b, c}]

Result:

{{1, 2, 3}, {2, 3, 1}}

Syed
  • 52,495
  • 4
  • 30
  • 85
  • 3
    ... or better still: Complement[a, b, c]. There is no need to apply the function twice, or to fold it over the input. – MarcoB May 11 '22 at 01:38
3

One possibility to achieve this is to join all sets to be replaced and then successively delete them (note also, do not use capitalized variable names, they are reserved for the system):

a = {{1, 2, 3}, {1, 3, 2}, {2, 1, 3}, {2, 3, 1}, {3, 1, 2}, {3, 2, 1}};
b = {{1, 3, 2}, {2, 1, 3}};
c = {{3, 1, 2}, {3, 2, 1}};

We set tmp to a and then delete the subsets:

tmp = a;
Scan[(tmp = DeleteCases[tmp, #]) &, Join[b, c], 1];
tmp

(* {{1, 2, 3}, {2, 3, 1}} *)

Daniel Huber
  • 51,463
  • 1
  • 23
  • 57