I have been searching for weeks on how to come up with piece of code which I could applied the cartesian product. Let\'s say I have two arrays :
int M[2]= {
Here is an implementation where the sequences of values is a parameter (rather than pre-known as in all the other implementations):
void CartesianRecurse(vector> &accum, vector stack,
vector> sequences, int index)
{
vector sequence = sequences[index];
for (int i : sequence)
{
stack.push_back(i);
if (index == 0)
accum.push_back(stack);
else
CartesianRecurse(accum, stack, sequences, index - 1);
stack.pop_back();
}
}
vector> CartesianProduct(vector> sequences)
{
vector> accum;
vector stack;
if (sequences.size() > 0)
CartesianRecurse(accum, stack, sequences, sequences.size() - 1);
return accum;
}
main() {
vector> sequences = { {1,2,7},{3,4},{5,6} };
vector> res = CartesianProduct(sequences);
// now do something with the result in 'res'.
}