# selecting from a group in c++

• July 15th, 2013, 10:05 PM
san1234
selecting from a group in c++
Hi,

I have N vectors which look like this:
[1→m] [m+1→2m] [2m+1→3m] [3m+1→4m] [4m+1→5m]..... [{(N-1)m}+1→Nm]

I want to select 1 element from each vector without duplication of any combinations.
Essentially only when all combinations are done with 1st element in first vector ,only then it should move to next element in first vector
say i have elements :[123] [456] [789]

my combinations should be like
147
148
149
157
158
159
167
168
169
247….

Also, i cant have any repetitions and only after all combinations of 1 are done only then the loop has to move to next combination ie 247 combination and so on.

i tried NCK (n choose k) command but it gave me random combinations.
how should i go about it with using minimal for loops?
thanks!
• July 16th, 2013, 01:35 AM
D_Drmmr
Re: selecting from a group in c++
Quote:

Originally Posted by san1234
my combinations should be like
147
148
149
157
158
159
167
168
169
247….

Also, i cant have any repetitions and only after all combinations of 1 are done only then the loop has to move to next combination ie 247 combination and so on.

So, how did you generate that list? Write down the exact steps you took that, if followed, would produce the entire list. Then you can translate that into C++ code, but you need to write the steps down on paper first.
• July 16th, 2013, 02:54 AM
superbonzo
Re: selecting from a group in c++
do you mean something like:

Code:

```#include <iostream> #include <vector> template< typename BiIter > bool next_indeces( BiIter from, BiIter to, typename std::iterator_traits<BiIter>::value_type extent ) {     if( from != to )     {         for( --to; ++*to == extent && to != from; --to )         {             *to = typename std::iterator_traits<BiIter>::value_type();         }         return *to != extent;     }     else         return false; } int main() {     int N = 3;     int M = 3;     std::vector<int> indeces( N );     do     {         for( int i = 0; i < N; ++i  )         {             std::cout << 1 + M * i + indeces[i] << ' ';         }         std::cout << std::endl;     }     while( next_indeces( indeces.begin(), indeces.end(), M ) ); }```
which gives

Code:

```1 4 7 1 4 8 1 4 9 1 5 7 1 5 8 1 5 9 1 6 7 1 6 8 1 6 9 2 4 7 2 4 8 2 4 9 2 5 7 2 5 8 2 5 9 2 6 7 2 6 8 2 6 9 3 4 7 3 4 8 3 4 9 3 5 7 3 5 8 3 5 9 3 6 7 3 6 8 3 6 9```
? clearly, note that if N and M are fixed at compile time and small, you can write this with just a bunch of for loops and/or some modulo arithmetic ...