Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cartesian Product in c++

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]= {1,2};
int J[3] = {0,1,2};

So the code will takes those two arrays in apply the rule M X J therefore we will have the pairs (1,0)(1,1)(1,2)(2,0)(2,1)(2,2) and I want the new result to be saved into a new array where each index in the array contains a pair , for example c[0] = (1,0). Help please :(

like image 323
mello Avatar asked Nov 07 '25 13:11

mello


1 Answers

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<vector<int>> &accum, vector<int> stack,
    vector<vector<int>> sequences, int index)
{
    vector<int> 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<vector<int>> CartesianProduct(vector<vector<int>> sequences)
{
    vector<vector<int>> accum;
    vector<int> stack;
    if (sequences.size() > 0)
        CartesianRecurse(accum, stack, sequences, sequences.size() - 1);
    return accum;
}

main() {
    vector<vector<int>> sequences = { {1,2,7},{3,4},{5,6} };
    vector<vector<int>> res = CartesianProduct(sequences);
    // now do something with the result in 'res'.
}
like image 83
Ofer Strichman Avatar answered Nov 10 '25 08:11

Ofer Strichman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!