I have this code which generates power set of an array of size 4 (number is just example, less combinations to write...).
#define ARRAY_SIZE 4
unsigned int i,
Write a function to generate all items of a fixed size. Note that the first such item is 1,..,k while the last is (n-k+1),..,n. This is very simple, you basically have to reimplement basic counting: you increment the last "digit", until you reach n. Then you reset to 1 and continue in the same fashion to its left.
Then just have k run from 1 (0) to n.
Here is one proposal for the internal algorithm. It's rather ugly, though.
void out(std::vector const& item) {
char del = '{';
for (auto it = item.begin(); it != item.end(); ++it) {
std::cout << del << *it;
del = ',';
}
std::cout << "}\n";
}
bool ascending(std::vector const& item) {
int last = 0;
for (auto it = item.begin(); it != item.end(); ++it) {
if (*it <= last)
return false;
last = *it;
}
return true;
}
void allk(int k, int n) {
std::vector item;
item.reserve(k+1);
for (int i = 1; i <= k; i++)
item.push_back(i);
bool valid = true;
while (valid) {
out(item);
do {
valid = false;
for (auto it = item.rbegin(); it != item.rend(); ++it) {
if (*it == n) {
*it = 1;
} else {
++*it;
valid = true;
break;
}
}
} while (valid && !ascending(item));
}
}