[Solved] All binary permutations of a fixed length in C


The answer goes like this.

  1. In C, the natural way to deal with an array of [0,1] is by treating them as bits.
  2. The 2^24 permutations of 24 bits are precisely the values of unsigned int from 0 to 2^24-1.
  3. So the question essentially is how to write the code based on that data structure.

Something like this.

int all_elements[160] = { ??? };
int all_marked_elements[24] = { ??? };
unsigned combo;
for (combo = 0; combo < 0x1000000; ++combo) {
  /* you probably want to take a copy of all_elements here */
  for (i = 0; i < 23; ++i) {
    unsigned bit = 1 << i;
    if (combo & bit) {
      int marked_element = all_marked_elements[i];
      /* do something I didn't understand, replacing element by its dual */
    }
    /* now call the operation and do something with the result */
  }
}

2

solved All binary permutations of a fixed length in C