Generating permuataions

I know how to generate all permutations of a list like:
{'h','e','k','p'}

But I am needing to know how to generate all permutations like:
{{'a','b'}, {'h','k','d'}, ..... }
such that the first character is either an 'a' or a 'b' and the second character is one of the three in the second list, etc.
There will be less than 600 000 permutations.
Nested for() loops? Of course there must exist a smarter way.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <string>

int main()
{
    std::string permutation(3, ' ');

    for (char c0: {'a', 'b'})
    {
        permutation[0] = c0;

        for (char c1: {'h', 'k', 'd'})
        {
            permutation[1] = c1;

            for (char c2: {'u', 'v', 'w'})
            {
                permutation[2] = c2;
                std::cout << permutation << '\n';
            }
        }
    }

    std::cout << std::endl;
}
ahu
ahv
ahw
aku
akv
akw
adu
adv
adw
bhu
bhv
bhw
bku
bkv
bkw
bdu
bdv
bdw


Edit: 600,000 permutations... hmm.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <iterator>
#include <vector>
#include <string>

template < typename ITERATOR >
void perms( std::string str, ITERATOR begin, ITERATOR end )
{
    if( begin != end )
        for( char c : *begin ) perms( str+c, std::next(begin), end ) ;
    else
    {
        static constexpr int WIDTH = 120 ;
        static int w = 0 ;

        w += str.size() + 3 ;
        if( w > WIDTH ) { std::cout << '\n' ; w = str.size() + 3  ; }
        std::cout << '"' << str << "\" " ;
    }
}

template < typename PERM_LIST > void perms( const PERM_LIST& list )
{ perms( "", list.begin(), list.end() ) ; }

int main()
{
    std::vector<std::string> perm_list = { "ab", "cdefg", "hij", "klmn", "opq", "rstuvw", "xyz" } ;
    perms( perm_list ) ;
}

http://coliru.stacked-crooked.com/a/c91ebb024f51de8b
Thank you guys very much.
Topic archived. No new replies allowed.