Search code examples
c++algorithmsortingmatharraylist

How to print the remaining set of numbers in C++?


Say there is a set U = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10} and I created a C++ program and I, using some logic printed the numbers { 1, 3, 6, 7, 9} (let's call it set A), so the remaining numbers are {2, 4, 5, 8, 1} (let's call it set B)

and U = A + B

Is there a direct way to print out set B numbers (B = U - A)? (Without actually reversing the logic from which I printed numbers of Set A)

Like if I printed even numbers, then the remaining are odd numbers and I can easily code to display odd numbers. But I am asking if there is another "direct" way of doing it?

Similarly, if I printed all prime numbers from 1-100 then I can kind of reverse the logic and print the numbers which were NOT printed (here, which were NOT prime), but I am NOT asking for that, I am asking is there a direct way to print the remaining set of numbers?

PS: I only know basic C++ and I have NOT yet started DSA (Data Structures and Algorithms) still any level answers are welcome, I will try hard to interpret it :)


Solution

  • Anytime you hear "find the missing elements" or "find the duplicate elements" type problem, you should immediately think "hash table". Do an internet search for Hash Table, but the wikipedia article has the basics.

    std::unordered_map and std::unordered_set are collection classes in C++ that are traditionally based on hash tables.

    Given a set U:

    unordered_set<int> U = { 1,2,3,4,5,6,7,8,9,10 };
    

    And a set A that is a subset of U:

    unordered_set<int> A = { 1,3,5,7,9 };
    

    Then B = U - A can be computed as

    unordered_set<int> B;
    for (int u  : U)               // for each item u in set U
    {
        if (A.find(u) == A.end())  // if u is not in "A"
        {
            B.insert(u);           // add it to "B".
        }
    }
    
    for (int b : B)
    {
        cout << b << endl;
    }
    

    If you need the output to be sorted, change the declaration of B from std::unordered_set to just std::set.