How to generate all possible permutations and combinations of a vector of chars in C++

1 Answer

0 votes
#include <iostream>
#include <vector>
#include <algorithm> // sort
#include <string>

// Function to print a vector of chars
void printVector(const std::vector<char>& vec) {
    for (char ch : vec) {
        std::cout << ch << ' ';
    }
    std::cout << '\n';
}

// Generate all permutations using STL
void generatePermutations(std::vector<char> charVector) {
    
    std::sort(charVector.begin(), charVector.end()); // Ensure lexicographic order

    do {
        printVector(charVector);
    } while (std::next_permutation(charVector.begin(), charVector.end()));
}

// Generate all combinations using bitmask
void generateCombinations(const std::vector<char>& charVector) {
    
    
    int size = charVector.size();
    // Loop over all possible non-empty subsets
    for (int mask = 1; mask < (1 << size); mask++) {
        std::vector<char> subset;
        for (int i = 0; i < size; i++) {
            if (mask & (1 << i)) {
                subset.push_back(charVector[i]);
            }
        }
        printVector(subset);
    }
}

int main() {
    std::vector<char> charVector = {'a', 'b', 'c'};

    std::cout << "All permutations:\n";
    generatePermutations(charVector);
    
    std::cout << "\nAll combinations:\n";
    generateCombinations(charVector);
}



/*
run:

All permutations:
a b c 
a c b 
b a c 
b c a 
c a b 
c b a 

All combinations:
a 
b 
a b 
c 
a c 
b c 
a b c 

*/

 



answered 1 day ago by avibootz
edited 1 day ago by avibootz

Related questions

...