Just as numbers can be added and multiplied, sets can be combined. A search engine combining “pages with word X” and “pages with word Y”, or a database query joining two tables, is doing set operations. This section defines the five basic ones.
The five operations
Sets with A∩B=∅ are called disjoint.
Operation
Logic word
Venn region
Commutative?
A∪B
or
both circles
yes
A∩B
and
overlap
yes
A∖B
and not
A without the overlap
no
A′
not
outside A
—
AΔB
exclusive or
both circles without the overlap
yes
Set operations in a program
E13 asks for a C program. A compact way to store a set of small numbers 0,…,31 is one unsigned int whose bit i is 1 when i is in the set. Then union is |, intersection is &, difference is & ~, and symmetric difference is ^ — exactly the Boolean algebra B32 of Block 1, Unit 3.
C · set_ops.c
#include <stdio.h>/* Print the elements 0..31 whose bits are 1 in s, e.g. {1, 2, 3} */static void print_set(const char *name, unsigned int s){ printf("%s = {", name); int first = 1; for (int i = 0; i < 32; i++) { if (s & (1u << i)) { printf(first ? "%d" : ", %d", i); first = 0; } } printf("}\n");}/* Build a set from an array of small numbers */static unsigned int make_set(const int *items, int n){ unsigned int s = 0; for (int i = 0; i < n; i++) { s |= 1u << items[i]; } return s;}int main(void){ const int a_items[] = {1, 2, 3, 4, 5, 6}; const int b_items[] = {4, 5, 6, 7, 8, 9}; unsigned int a = make_set(a_items, 6); unsigned int b = make_set(b_items, 6); print_set("A union B", a | b); print_set("A intersect B", a & b); print_set("A minus B", a & ~b); print_set("B minus A", b & ~a); print_set("A delta B", a ^ b); return 0;}
Output
A union B = {1, 2, 3, 4, 5, 6, 7, 8, 9}A intersect B = {4, 5, 6}A minus B = {1, 2, 3}B minus A = {7, 8, 9}A delta B = {1, 2, 3, 7, 8, 9}
Key takeaways
A∪B: in either; A∩B: in both; A∖B: in A but not B; A′: in U but not A.
AΔB=(A∖B)∪(B∖A): in exactly one of the two sets.
Union, intersection and symmetric difference are commutative; difference is not.
A∖B=B∖A and A∩B=A∪B both hold only when A=B.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Prove that A∩B=A∪B implies A=B.
Show worked answer
Assume A∩B=A∪B. Take any x∈A. Then x∈A∪B=A∩B, so x∈B; hence A⊆B. Similarly, any x∈B is in A∪B=A∩B, so x∈A; hence B⊆A. Therefore A=B. (Conversely, if A=B then A∩B=A=A∪B.)
MCA Online notes are made for reading on screen. Open https://mcastudy.online/mcs-212/sets-relations-and-functions/operations-on-sets/ to read this page.