Artemis Artemis - 14 days ago 6
C++ Question

how to generate the string sequence in C++

I am trying to do the following on my computer but not getting it to perform, like say I have a name of a person and I want to make a different combinations of the letters in his name:

NAME ABC
ABC
/ | \
A B C
/|\ / | \ /| \
AA AB AC BA BB BC CA CB CC
. . .
. . .


I want to make combinations of the above name, for example:

ABC A B C AA AB AC BA BB BC CA CB CC.... AAA... BBB... CCC...


How can I do this in C++?

I wrote the following code for it:

string c = "ABC";
for (i = 0; i < c.length(); i++)
c.at(i);


But it only generated
A, B, C
. How do I generate
AB, AA, AC, ...
?

Answer

Here's a solution involving lovely recursive templates:

#include <iostream>
#include <string>

template <int Depth>
void print_combinations(const std::string& name, const std::string& prefix = "")
{
    for (int i=0; i < name.size(); i++) {
        std::cout << prefix << name[i] << " ";
        print_combinations<Depth - 1>(name, prefix + name[i]);
    }
}

template <>
void print_combinations<0>(const std::string&, const std::string&)
{
}

int main()
{
    std::string name = "ABC";

    print_combinations<4>(name);
}

For Depth=4 (as above), it prints

A AA AAA AAAA AAAB AAAC AAB AABA AABB AABC AAC AACA AACB AACC AB ABA ABAA ABAB ABAC ABB ABBA ABBB ABBC ABC ABCA ABCB ABCC AC ACA ACAA ACAB ACAC ACB ACBA ACBB ACBC ACC ACCA ACCB ACCC B BA BAA BAAA BAAB BAAC BAB BABA BABB BABC BAC BACA BACB BACC BB BBA BBAA BBAB BBAC BBB BBBA BBBB BBBC BBC BBCA BBCB BBCC BC BCA BCAA BCAB BCAC BCB BCBA BCBB BCBC BCC BCCA BCCB BCCC C CA CAA CAAA CAAB CAAC CAB CABA CABB CABC CAC CACA CACB CACC CB CBA CBAA CBAB CBAC CBB CBBA CBBB CBBC CBC CBCA CBCB CBCC CC CCA CCAA CCAB CCAC CCB CCBA CCBB CCBC CCC CCCA CCCB CCCC

Comments