Artemis
Artemis

Reputation: 141

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, ...?

Upvotes: 0

Views: 3461

Answers (2)

Tristan Brindle
Tristan Brindle

Reputation: 16824

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

Upvotes: 2

Shikhar Subedi
Shikhar Subedi

Reputation: 616

you can do this

string c='ABC';
int n=c.length();

for(int i=0;i<n;i++)
{
  std::cout<<c[i]<<" ";

  for(int j=0 ; j< n ;j++)
  {
      std::cout<<c[i]<<c[j]<<" ";
  }
}

The output is: A AA AB AC B BA BB BC C CA CB CC

If you want the three letter combinations, add a third for loop inside the second for loop with the same end points like

for(int k=0;k<n;k++) and inside the for loop cout<<c[i]<<c[j]<<c[k]<<" "

Upvotes: 3

Related Questions