This question already has an answer here:
- combination and permutation in C++ 4 answers
I am looking for the implementation of Permutation, Combination and PowerSet using C+++
This question already has an answer here:
I am looking for the implementation of Permutation, Combination and PowerSet using C+++
Using STL:
Permutation:
using std::next_permutation
template <typename T>
void Permutation(std::vector<T> v)
{
std::sort(v.begin(), v.end());
do {
std::copy(v.begin(), v.end(), std::ostream_iterator<T>(std::cout, " "));
std::cout << std::endl;
} while (std::next_permutation(v.begin(), v.end()));
}
Combination:
template <typename T>
void Combination(const std::vector<T>& v, std::size_t count)
{
assert(count <= v.size());
std::vector<bool> bitset(v.size() - count, 0);
bitset.resize(v.size(), 1);
do {
for (std::size_t i = 0; i != v.size(); ++i) {
if (bitset[i]) {
std::cout << v[i] << " ";
}
}
std::cout << std::endl;
} while (std::next_permutation(bitset.begin(), bitset.end()));
}
PowerSet:
Note that if the size if less than the number of bit of your integer, you may you that integer instead of vector<bool>
. If the size is known at compile time, prefer std::bitset<N>
over std::vector<bool>
bool increase(std::vector<bool>& bs)
{
for (std::size_t i = 0; i != bs.size(); ++i) {
bs[i] = !bs[i];
if (bs[i] == true) {
return true;
}
}
return false; // overflow
}
template <typename T>
void PowerSet(const std::vector<T>& v)
{
std::vector<bool> bitset(v.size());
do {
for (std::size_t i = 0; i != v.size(); ++i) {
if (bitset[i]) {
std::cout << v[i] << " ";
}
}
std::cout << std::endl;
} while (increase(bitset));
}
Live example
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
using namespace std;
void
Permutation(vector < char >set, vector < char >path, vector < bool > visited)
{
if (set.size() == path.size()) {
copy(path.begin(), path.end(), ostream_iterator < char >(cout, " "));
cout << endl;
return;
}
for (size_t i = 0; i < set.size(); ++i) {
if (!visited[i]) {
visited[i] = true;
path.push_back(set[i]);
Permutation(set, path, visited);
visited[i] = false;
path.pop_back();
}
}
}
void
Combination(vector < char >set, vector < char >path, size_t start, size_t maxlen)
{
if (maxlen == path.size()) {
copy(path.begin(), path.end(), ostream_iterator < char >(cout, " "));
cout << endl;
return;
}
for (size_t i = start; i < set.size(); ++i) {
path.push_back(set[i]);
Combination(set, path, ++start, maxlen);
path.pop_back();
}
}
void
PowerSet(vector < char >set)
{
for (int i = 0; i <= set.size(); ++i) {
vector < char >path;
Combination(set, path, 0, i);
}
}
int
main()
{
vector < char >vc {
'A', 'B', 'C', 'D'
};
vector < char >path;
vector < bool > visited(4, false);
cout << "\n------PERMUTATION----------\n";
Permutation(vc, path, visited);
cout << "\n------COMBINATION----------\n";
Combination(vc, path, 0, 3);
cout << "\n------POWERSET-------------\n";
PowerSet(vc);
return 0;
}