fork download
  1. #include <iostream>
  2. #include <iterator>
  3. #include <algorithm>
  4. #include <string>
  5.  
  6. char letters[] = {'a', 'b', 'c'};
  7.  
  8. template <typename T, std::size_t N>
  9. std::size_t array_size(T (&)[N])
  10. { return N; }
  11.  
  12. bool next(std::string& in)
  13. {
  14. for(std::size_t i = 0; i < in.size(); ++i)
  15. if(in[i] == letters[array_size(letters) - 1]){ //if current letter is last in set ...
  16. in[i] = letters[0]; //Then we assign first letter and let loop continue
  17. } else {
  18. std::size_t pos = std::distance(std::begin(letters),
  19. std::find(std::begin(letters), std::end(letters), in[i]));
  20. in[i] = letters[++pos]; //Else we assign next letter in set and return true
  21. return true; //As indication that it is not the last possible string
  22. }
  23. return false; //If loop finished, we exhausted all strings
  24. }
  25.  
  26. void print_all()
  27. {
  28. constexpr std::size_t max = 4;
  29. for(std::size_t size = 1; size <= max; ++size) {//Generate sequences of all possible length
  30. //Create string of correspomding length. Note that we CANNOT use space as initializer
  31. //Or nothing would work at all.
  32. std::string guess(size, letters[0]);
  33. bool again = false;
  34. do { //Inner loop, generates all possible variation of given length
  35. again = next(guess); //Generate next string
  36. std::cout << guess << '\n';
  37. } while( again );
  38. std::cout << '\n';
  39. }
  40. }
  41.  
  42. int main ()
  43. {
  44. print_all();
  45. }
  46.  
Success #stdin #stdout 0s 3228KB
stdin
Standard input is empty
stdout
b
c
a

ba
ca
ab
bb
cb
ac
bc
cc
aa

baa
caa
aba
bba
cba
aca
bca
cca
aab
bab
cab
abb
bbb
cbb
acb
bcb
ccb
aac
bac
cac
abc
bbc
cbc
acc
bcc
ccc
aaa

baaa
caaa
abaa
bbaa
cbaa
acaa
bcaa
ccaa
aaba
baba
caba
abba
bbba
cbba
acba
bcba
ccba
aaca
baca
caca
abca
bbca
cbca
acca
bcca
ccca
aaab
baab
caab
abab
bbab
cbab
acab
bcab
ccab
aabb
babb
cabb
abbb
bbbb
cbbb
acbb
bcbb
ccbb
aacb
bacb
cacb
abcb
bbcb
cbcb
accb
bccb
cccb
aaac
baac
caac
abac
bbac
cbac
acac
bcac
ccac
aabc
babc
cabc
abbc
bbbc
cbbc
acbc
bcbc
ccbc
aacc
bacc
cacc
abcc
bbcc
cbcc
accc
bccc
cccc
aaaa