Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,656 questions

55,396 answers

573 users

How to generate the power set of {1,2,3,4} in C++

1 Answer

0 votes
#include <iostream>
#include <vector>

// The power set of a set S is the set of all subsets of S, written as P(S).

/*
    Function: generatePowerSet
    Purpose:  Create the power set of a given vector<int> using bit manipulation.
              This is efficient because each subset corresponds to a unique binary
              representation of numbers from 0 to (2^n - 1).

    Explanation of algorithm:
    - For a set of size n, there are 2^n possible subsets.
    - Each number from 0 to (2^n - 1) represents one subset.
    - For each bit position j in number i:
        - If bit j is ON (i.e., (i & (1 << j)) != 0), include element[j] in the subset.
*/
std::vector<std::vector<int>> generatePowerSet(const std::vector<int>& set) {
    std::vector<std::vector<int>> powerSet;
    int n = set.size();
    int totalSubsets = 1 << n;  // 2^n subsets

    for (int mask = 0; mask < totalSubsets; ++mask) {
        std::vector<int> subset;

        // Check each bit of mask
        for (int bit = 0; bit < n; ++bit) {
            if (mask & (1 << bit)) {
                subset.push_back(set[bit]);
            }
        }

        powerSet.push_back(subset);
    }

    return powerSet;
}

int main() {
    std::vector<int> inputSet = {1, 2, 3, 4};

    // Generate the power set
    std::vector<std::vector<int>> result = generatePowerSet(inputSet);

    // Print the power set
    std::cout << "Power set of {1,2,3,4}:\n";
    for (const auto& subset : result) {
        std::cout << "{ ";
        for (int num : subset) {
            std::cout << num << " ";
        }
        std::cout << "}\n";
    }
}


/*
run:

Power set of {1,2,3,4}:
{ }
{ 1 }
{ 2 }
{ 1 2 }
{ 3 }
{ 1 3 }
{ 2 3 }
{ 1 2 3 }
{ 4 }
{ 1 4 }
{ 2 4 }
{ 1 2 4 }
{ 3 4 }
{ 1 3 4 }
{ 2 3 4 }
{ 1 2 3 4 }

*/

 



answered Jul 9 by avibootz
...