Cartesian Product in c++

后端 未结 4 790
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-15 02:16

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]= {         


        
4条回答
  •  心在旅途
    2020-12-15 02:49

    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'.
    }
    

提交回复
热议问题