'How to binary fill a 2D array with all possible column combinations? (c++) [closed]

I want to fill a 2D array that is initialized with 0's to a binary array that indicates all possible combinations of the columns. As input variable, I only have the number of alternatives. From this input, I calculate the possible combinations of the alternatives. Next, I create a 2D array with the number of rows equal to the number of possible combinations and with the number of columns equal to the number of alternatives that was given as input. I initialize all values of the 2D arrays with a 0. Now I try to transform this 2D array to an array with 0's and 1's, indicating all possible combinations of alternatives. Below I have attached a practical example that clarifies the goal of the code.

Can anyone help my with writing the for loops that can solve my problem? Thanks in advance!

Practical example



Solution 1:[1]

I think 0000 is one of the combinations, too.

You can find the patterns:

Each column repeats k 0s then k 1s where k = 2^(j+1).

E.g. 4 bits -> 2^4 combinations

int a[16][4] = {0};
for (int i = 0; i < 16; i++) {
    for (int j = 0; j < 4; j++) {
        int k = (int)pow(2, j+1);
        if (i % k + 1 > k / 2) {
            a[i][j] = 1;
        }
    }
}

Output:

0000
1000
0100
1100
0010
1010
0110
1110
0001
1001
0101
1101
0011
1011
0111
1111

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1