Search code examples
c++algorithmmathcombinationsnested-loops

C++, not in order combination of array elements


I am trying to get all combinations of an array with C++ such that

double* list1 = new double[size];

Items in that array is {1,2,3,4,5}

I need to add all possible combinations into a stack, such as:

1+2, 1+2+3, 1+2+3+4,1+2+3+4+5, 1+3, 1+3+4, 1+3+4+5, 1+4, 1+4+5, 1+5...

the problem I am running into is I am doing this through 2 for loops and a while loop

for(int i = 0; i < size - 1; i++)
{
    for(int j = i; j < size - 1; j++)
    {
        double temp = list1[i] + list1[j + 1];
        list1combos.push(temp);
        int k = j + 2;
        while (k <= size - 1)
        {
            temp = temp + list1[k];
            list1combos.push(temp);
            k++;
        }
    }
}

I can get the ones I listed above but I have no clue how to code in combinations such as 1+3+5, or 1+2+5

Please advise on how to get those combinations, thanks stackoverflow!


Solution

  • Since the order does not matter, I would suggest having an array of the same size as your x and perform a binary increment on it, i.e. you start with the array inited to only 0s and count until you have only 1s. For every addition of a 1 you would pick a permutation from your x array.

    First iteration:
    0 0 0 0 0 -> empty
    Second iteration:
    0 0 0 0 1 -> you pick 5
    3rd iteration:
    0 0 0 1 0 -> you pick 4
    4th iteration:
    0 0 0 1 1 -> you pick 4 and 5
    And so on until you reach:
    1 1 1 1 1 -> you pick 1, 2, 3, 4 and 5