Mathematics | Set Operations (Set theory)

Union
Union of the sets A and B, denoted by A ∪ B, is the set of distinct element belongs to set A or set B, or both.

AUB

Above is the Venn Diagram of A U B.

Example : Find the union of A = {2, 3, 4} and B = {3, 4, 5};
Solution : A ∪ B = {2, 3, 4, 5}.

 



Intersection
The intersection of the sets A and B, denoted by A ∩ B, is the set of elements belongs to both A and B i.e. set of the common element in A and B.

AinterB

Above is the Venn Diagram of A ∩ B.

Example: Consider the previous sets A and B. Find out A ∩ B.
Solution : A ∩ B = {3, 4}.

 

Disjoint
Two sets are said to be disjoint if their intersection is the empty set .i.e sets have no common elements.

AdijointB

Above is the Venn Diagram of A disjoint B.



For Example
Let A = {1, 3, 5, 7, 9} and B = { 2, 4 ,6 , 8} .
A and B are disjoint set both of them have no common elements.

 

Set Difference
Difference between sets is denoted by ‘A – B’, is the set containing elements of set A but not in B. i.e all elements of A except the element of B.

A-B

Above is the Venn Diagram of A-B.

 

Complement
Complement of a set A, denoted by

A^\complement

, is the set of all the elements except A. Complement of the set A is U – A.

Acomplemnt



Above is the Venn Diagram of Ac

Addition & Subtraction
Addition of sets A and B, referred to as Minknowski Addition, is the set in whose elements are the sum of each possible pair of elements from the 2 sets (that is one element is from set A and other is from set B).

Set subtraction follows the same rule, but with the subtraction operation on the elements. It is to be observed that these operations are operable only on numeric data types. Even if operated otherwise, it would only be a symbolic representation without any significance. Further, it can be seen easily that set addition is commutative, while subtraction is not.

For Additions and consequently Subtraction, please refer this answer.


    Formula:

  1. A\cup B =n(A) + n(B) - n(A\cap B)

  2. A-B=A\cap \bar{B}


    Properties of Union and Intersection of sets:

  1. Associative Properties: A ∪ (B ∪ C) = (A ∪ B) ∪ C and A ∩ (B ∩ C) = (A ∩ B) ∩ C
  2. Commutative Properties: A ∪ B = B ∪ A and A ∩ B = B ∩ A
  3. Identity Property for Union: A ∪ φ = A
  4. Intersection Property of the Empty Set: A ∩ φ = φ
  5. Distributive Properties: A ∪(B ∩ C) = (A ∪ B) ∩ (A ∪ C) similarly for intersection.



  6. Example : Let A = {0, 2, 4, 6, 8} , B = {0, 1, 2, 3, 4} and C = {0, 3, 6, 9}. What are A ∪ B ∪ C and A ∩ B ∩ C ?

    Solution: Set A ∪ B &cup C contains elements which are present in at least one of A, B, and C.

    A ∪ B ∪ C = {0, 1, 2, 3, 4, 6, 8, 9}.

    Set A ∩ B ∩ C contains an element which is present in all the sets A, B and C .i.e { 0 }.

     

    See this for Set Theory Introduction.

    Given below is the source code for some of the basic set operations. By default, the program works only on integers, but can be modified in the main function to run for other data types also. But in the latter case, Addition and Subtraction operations will not give any defined outputs.

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    #include <iostream>
    #include <string>
    using namespace std;
      
    // defining class set
    template <typename T> class Set {
    private:
      //an array of elemetns of type T which will be present in the set
      T elements[100];
      //cardinality of the set
      int cardinality;
      
    public:
      //all the methods have been defined after main function
      // constructors
      Set();
      
      //for insertion
      void insert(const T data);
      
      //for deletion of an element
      void delete_element(const T data);
      
      //to search if element present
      int is_present(const T data) const;
      
      //getter functions- returns the cardinalty of the set
      int get_cardinality() const;
      
      //displays the set
      void display() const;
      
      //to build the set by taking input through stdin
      void build_set();
      
      // return the address to the array of elements
      const T *get_elements() const {
        const T *ptr = &elements[0];
        return ptr;
      }
    };
      
    // now defining fucntions to perform on them
      
    //function to perform intersection of 2 sets
    template <typename T>
    Set<T> intersection_of_sets(const Set<T> &set1, const Set<T> &set2);
      
    // union of 2 sets
    template <typename T>
    Set<T> union_of_sets(const Set<T> &set1, const Set<T> &set2);
      
    // difference of 2 sets, performs set1-set2
    template <typename T> Set<T> difference(const Set<T> &set1, const Set<T> &set2);
      
    // symmetric differnce
    template <typename T>
    Set<T> symm_difference(const Set<T> &set1, const Set<T> &set2);
      
    template <typename T>
    Set<T> addition_of_sets(const Set<T> &set1, const Set<T> &set2);
      
    template <typename T>
    Set<T> subtraction_of_sets(const Set<T> &set1, const Set<T> &set2);
      
    int main() {
      
      // by defualt making a set of integers
      // but same can be done for any data type
      Set<int> set1, set2, set3;
      //the next 2 statements can work with user given input
      //For the current program, we will insert elements manually
      //set1.build_set();
      //set2.build_set();
      set1.insert(2);
      set1.insert(3);
      set1.insert(4);
        
      set2.insert(3);
      set2.insert(4);
      set2.insert(5);
      set2.insert(6);
      
      cout << endl << "Addition of Set1 and Set2" << endl;
      set3 = addition_of_sets(set1, set2);
      set3.display();
      
      cout << endl << "Subtraction of Set1 and Set2" << endl;
      set3 = subtraction_of_sets(set1, set2);
      set3.display();
      
      cout << endl << "union of Set1 and Set2" << endl;
      set3 = union_of_sets(set1, set2);
      set3.display();
      
      cout << endl << "Intersection of Set1 and Set2" << endl;
      set3 = intersection_of_sets(set1, set2);
      set3.display();
      
      cout << endl << "Difference of Set1 and Set2" << endl;
      set3 = difference(set1, set2);
      set3.display();
        
      cout << endl << "Difference of Set2 and Set1" << endl;
      set3 = difference(set2, set1);
      set3.display();
      
      cout << endl << "Symmetric Difference of Set1 and Set2" << endl;
      set3 = symm_difference(set1, set2);
      set3.display();
    }
      
    //Constructor of Set class
    //creates an empty set with cardinality equal to zero
    template <typename T> Set<T>::Set() { cardinality = 0; }
      
    //Method to insert an element in the set
    //given an element data, add it to the set only if it's not present already
    template <typename T> void Set<T>::insert(const T data) {
      if (is_present(data) == -1) {
        //data is not present, so increase the cardinality by 1 and insert data in set
        elements[cardinality] = data;
        ++cardinality;
      }
    }
      
    //Method to take a list of inputs through stdin and insert them in the set
    //using insert method
    template <typename T> void Set<T>::build_set() {
      //no of elements to be entered in the current call
      int n = 0;
      cout << endl << "How many elements in this set?  ";
      cin >> n;
      
      //using the insert() method, add the elements to the set
      cout << endl << "Enter the elements separated by space: " << endl;
      for (int i = 0; i < n; ++i) {
        T d = 0;
        cin >> d;
        insert(d);
      }
    }
      
    //Method to delete a given element from the set
    template <typename T> void Set<T>::delete_element(const T data) {
      //nothing can be deleted from an empty set, so checking cardinality
      if (cardinality != 0) {
        //if the given key is present, get the index of key using is_present() method
        int index = is_present(data);
          
        //if -1 is returned, element is not present in the set
        if (index != -1) {
          for (int i = index; i < (cardinality - 2); ++i) {
            elements[i] = elements[i + 1];
          }
        //print message on successful deletion
          printf("%d successfully deleted from the set\n", data);
        } else {
          //print message to indicate that element not present in set
          printf("Element %d not present in set!\n", data);
        }
      }
      
      else {
        //print message if the set is empty
        printf("Set is already empty!\n");
      }
    }
      
    //search for the given key 'data' in the set through linear search
    //if present, return the index at which key is present
    //else return -1
    template <typename T> int Set<T>::is_present(const T data) const {
      for (int i = 0; i < (cardinality); ++i) {
        if (elements[i] == data) {
          return i;
        }
      }
      
      return -1;
    }
      
      
    //returns the current cardinality of the set
    template <typename T> int Set<T>::get_cardinality() const {
      return cardinality;
    }
      
    //displays the contents of the set by traversing it once linearly
    template <typename T> void Set<T>::display() const {
      if (cardinality == 0) {
        //print phi chracter to indicate empty set
        printf("?\n");
        return;
      }
        //else traverse and print
      for (int i = 0; i < cardinality; ++i) {
        cout << elements[i] << " ";
      }
      printf("\n");
    }
      
    //Function to perform the intersection of two sets guven as parameter
    //returns the resultant set
    template <typename T>
    Set<T> intersection_of_sets(const Set<T> &set1, const Set<T> &set2) {
      const T *ptr1 = nullptr;
      //get the address of the array elements
      ptr1 = set1.get_elements();
      
      //declaring the resultant set
      Set<T> set3;
      
      //iterate over the first set
      //if a given element is present in other set also
      //then add it to resultant set, otherwise move ahead
      int n1 = set1.get_cardinality();
      for (int i = 0; i < n1; ++i) {
        if (set2.is_present(ptr1[i]) != -1) {
          set3.insert(ptr1[i]);
        }
      }
      
      return set3;
    }
      
    //Function to perform the union of two sets given as parameter
    //returns the resultant set
    template <typename T>
    Set<T> union_of_sets(const Set<T> &set1, const Set<T> &set2) {
      const T *ptr1 = nullptr, *ptr2 = nullptr;
      ptr1 = set1.get_elements();
      ptr2 = set2.get_elements();
      
      Set<T> set3;
      
      //iterate over the first set and add all the elements to set3
      //then iterate over the second set checking whether the element
      //to be added is already present or not
      //if it is already present, skip
      //else add the element to the resultant set
        
      //first set
      int n1 = set1.get_cardinality(), n2 = set2.get_cardinality();
      for (int i = 0; i < n1; ++i) {
        set3.insert(ptr1[i]);
      }
      
      //second set while checking for duplicates
      for (int i = 0; i < n2; ++i) {
        if (set3.is_present(ptr2[i]) == -1) {
          set3.insert(ptr2[i]);
        }
      }
      
      return set3;
    }
      
    //Returns a difference of two sets
    //difference of set1 and set2 is the set of elements present in set1 but not in set2
    template <typename T>
    Set<T> difference(const Set<T> &set1, const Set<T> &set2) {
      const T *ptr1 = nullptr;
      ptr1 = set1.get_elements();
      Set<T> set3;
      
      int n1 = set1.get_cardinality();
      
      for (int i = 0; i < n1; ++i) {
        if (set2.is_present(ptr1[i]) == -1) {
          set3.insert(ptr1[i]);
        }
      }
      
      return set3;
    }
      
    //performs 2 difference operations
    //difference of set1 and set2
    //and difference of set2 and set1
    //returns the union of the 2 sets obtained above
    template <typename T>
    Set<T> symm_difference(const Set<T> &set1, const Set<T> &set2) {
      Set<T> s1 = difference(set1, set2);
      Set<T> s2 = difference(set2, set1);
        
      //returning union of s1 and s2
      return union_of_sets(s1, s2);
    }
      
    //performs the addition of sets as described in the theory
    template <typename T>
    Set<T> addition_of_sets(const Set<T> &set1, const Set<T> &set2) {
      const T *ptr1 = nullptr, *ptr2 = nullptr;
      ptr1 = set1.get_elements();
      ptr2 = set2.get_elements();
      
      Set<T> set3;
      
      int n1 = set1.get_cardinality(), n2 = set2.get_cardinality();
        
      //iterate over both the sets, adding all possible
      //pairs (unordered) elements and inserting the obtained sum
      //in the resultant set
      for (int i = 0; i < n1; ++i) {
        for (int j = 0; j < n2; ++j) {
          T temp = ptr1[i] + ptr2[j];
          set3.insert(temp);
        }
      }
      
      return set3;
    }
      
    //performs the subtractoin of sets (set1-set2 only) as described in the theory
    template <typename T>
    Set<T> subtraction_of_sets(const Set<T> &set1, const Set<T> &set2) {
      const T *ptr1 = nullptr, *ptr2 = nullptr;
      ptr1 = set1.get_elements();
      ptr2 = set2.get_elements();
      
      Set<T> set3;
      
      int n1 = set1.get_cardinality(), n2 = set2.get_cardinality();
      
      //iterate over both the sets, subtracting of all elemets of set2
      //from all elements of set1
      //and inserting the obtained difference
      //in the resultant set
      for (int i = 0; i < n1; ++i) {
        for (int j = 0; j < n2; ++j) {
          T temp = ptr1[i] - ptr2[j];
          set3.insert(temp);
        }
      }
      
      return set3;
    }

    chevron_right

    
    

    Output:

    Addition of Set1 and Set2
    5 6 7 8 9 10 
    
    Subtraction of Set1 and Set2
    -1 -2 -3 -4 0 1 
    
    union of Set1 and Set2
    2 3 4 5 6 
    
    Intersection of Set1 and Set2
    3 4 
    
    Difference of Set1 and Set2
    2 
    
    Difference of Set2 and Set1
    5 6 
    
    Symmetric Difference of Set1 and Set2
    2 5 6
    

     

    Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

    Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.




    My Personal Notes arrow_drop_up

    Article Tags :

    10


    Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.