The trivial algorithm with an arbitrary number of levels (also does a lot of copying strings):
class StringCombinations {
public:
// filled somehow
std::vector<std::pair<char, char> > choices;
void printStrings(size_t level, std::string prefix) {
assert(level < choices.size());
if (level == choices.size() - 1) {
cout << prefix << choices[i].first();
cout << prefix << choices[i].second();
} else {
printStrings(level +1, prefix + choices[i].first());
printStrings(level +1, prefix + choices[i].second());
}
}
}
called like this:
StringCombinations sc;
// Set the choices table somehow.
...
sc.printStrings(0, "");
the choices table could, of course, also be another method parameter that is passed as const-reference, if it is more convenient for you to have a static method for this.
--
A better alternative (just the generalization to n levels of what otehr answers proposed for 3 levels) without all that copying for the recursive calls (less understandable, though):
Note that you can, of course, repalce cout <<
with mystring +=
if you do not print directly.
// all strings have size 2, 0'th char and 1'st char correspond to the choices
std::vector<std::string> choices;
void printStrings() {
for (size_t i = 0; i < static_cast<size_t>(pow(2, choices.size())); ++i) {
for (size_t j = 0; j < choices.size(); ++j) {
// Checks the bit in i (from the right) that fits the current level (j).
cout << choices[j][i & (j << x)];
// 2^#levels different values of i, ensure as many different outcomes
// (disregarding trivial choices between, e.g., 'a' and 'a'
}
}
}