When calculations are being performed on each element of the power set, it can be advantageous if each set differs from its predecessor by as few elements as possible. One can produce the subsets in order such that each subset differs from its predecessor by only one element. The characteristic vectors of sets in this order are called Gray codes.

These are the Gray codes in order for a set of 3 elements:

[0, 0, 0] [1, 0, 0] [1, 1, 0] [0, 1, 0] [0, 1, 1] [1, 1, 1] [1, 0, 1] [0, 0, 1]

They correspond to the following subsets. Notice how each subset differs from its predecessor by only 1 element:

{} {a} {a, b} {b} {b, c} {a, b, c} {a, c} {c}

In order to go from one Gray code to its successor, it is necessary to find which single value in the array to change from 1 to 0, or vice-versa.

The rules for finding the index of this element `j`

are based on the number of 1s in the current code, `k`

, as follows:

- If
`k`

is even, then`j`

= 0 - If
`k`

is odd, then`j`

is the index of the first cell that follows the first 1

unsigned int next_subset_gray(unsigned int *ar, size_t n) { /* Find the number of 1s, and the first 1 */ unsigned int i; unsigned int k = 0; int first_1 = -1; unsigned int finished = 0; for (i = 0; i < n; i++) { if (ar[i] == 1) { k++; if (first_1 == -1) { first_1 = i; } } } /* Flip the relevant digit */ if (k % 2 == 0) { /* First digit */ ar[0] ^= 1; } else if (first_1 < n - 1) { /* Digit after the first 1 */ ar[first_1 + 1] ^= 1; } else { /* Last digit */ ar[n - 1] = 0; finished = 1; } return finished == 0; }