all permutations with repetition of vectors of strings.

Hi all I am trying to convert this loop that work exactly as I need on chars of strings.

1
2
3
4
5
6
7
8
9
10
 void Permutenr(const string& input, string output, int r)
 {
      if(output.length() == r) {
          cout << output << endl;
      } else {
           for(int i=0; i<input.length(); ++i){
                Permutenr(input, output + input[i], r);
           }
      }
 }


to use vectors.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
void Permutenr( vector<string> &input, vector<string> output, int r)
{
    if(output.size () == r) {

        for(auto &item : output){
            cout << item << " ";
        }cout << endl;

    } else {
        for(int i=0; i<input.size (); ++i)
                output.push_back (input[i]);
            Permutenr(input,output, r);
        }
}


and I am not getting the expected output.

using

vector<string> v{"1","2"}

I am getting

1 1

not (order of output not written explicitly)

1 1

1 2

2 1

2 2

Last edited on
output + input[i] does not modify the object output

output.push_back (input[i]); does.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
template < typename SEQUENCE >
void Permutenr( const SEQUENCE& input, SEQUENCE output, std::size_t r )
 {
    if( output.size() == r ) {

        for( const auto& v : output ) {

            std::cout << v << ' ' ;
        }
        
        std::cout << '\n' ;
    }

    else {

        for( std::size_t i=0; i < input.size(); ++i ) {

            SEQUENCE temp_output = output ; // we do not want to modify output
            temp_output.push_back( input[i] ) ;
            Permutenr( input, temp_output, r);
        }
    }
 }

http://coliru.stacked-crooked.com/a/e0a2eea6a4e4716a
@JLBorges Thanks again for your help with the last two questions I had.
I finished up the program tonight and it all works as intended. Pretty spectacular!
Topic archived. No new replies allowed.