Imagine we have a vector with only unique values and would like to generate all pairs. The algorithm to do so is:
vector< int > data;
// ... pushback some data
vector< vector< int > > pairs;
for( size_t i = 0; i < data.size() - 1; ++i )
{
for( size_t j = i + 1; j < data.size(); ++j )
{
vector< int > pair;
pair.push_back( data[i] );
pair.push_back( data[j] );
pairs.push_back( pair );
}
}
Now, for triples the algorithm changes to:
vector< int > data;
// ... pushback some data
vector< vector< int > > triples;
for( size_t i = 0; i < data.size() - 2; ++i )
{
for( size_t j = i + 1; j < data.size() - 1; ++j )
{
for( size_t k = j + 1; k < data.size(); ++k )
{
vector< int > triple;
triple.push_back( data[i] );
triple.push_back( data[j] );
triple.push_back( data[k] );
triples.push_back( triple );
}
}
}
It's fairly easy to come up with the code for quadruples and other tuple types.
Could someone show me how to achieve a general algorithm to generate all sort of tuples? And since we are at it how can I calculate the number of tuples given the number of elements in a vector? For pairs the formula is n(n-1)/2.
Thanks!