learning_c/combinations/src/combinations.c

30 lines
833 B
C

/* calculates all subsets of the string comb by assigning eatch letter a position in a binary number and counting up. */
#include <stdio.h>
#include <string.h>
// #define DEBUG
int main() {
char* comb = "ABCD";
int count = strlen(comb);
// that bitshifting is the same is squaring count
int permutations = (1 << count);
printf("string is %s\nthere are %d permutations", comb, permutations);
for (unsigned char i = 0; i < permutations; i++) {
for (unsigned char j = 0; j < 4; j++) {
// when j=0, will result in 0b0001, when j=1, 0b0010, j=2 0b0100.
unsigned char mask = 1 << j;
#ifdef DEBUG
printf(" j=%x mask=%x, postmask=%x, i=%x", j, mask, (i & mask), i);
#endif /* ifdef DEBUG */
if ((i & mask) != 0) {
printf(" %c", comb[j]);
}
}
printf("\n");
}
return 0;
}