2
1
Fork 0
aoc2021/03/solution_1.c
2021-12-03 21:30:10 +01:00

32 lines
794 B
C

#include <stdio.h>
#include <string.h>
int main(void) {
FILE *fp = fopen("input.txt", "r");
char buf[16];
unsigned rlen = sizeof(buf) - 1;
unsigned bitcnt[2][sizeof(buf) - 1] = {0};
size_t gamma = 0, epsilon = 0;
while (fgets(buf, sizeof(buf), fp) != NULL) {
for (size_t i = 0; i < rlen; i++) {
if (buf[i] == '0')
bitcnt[0][i]++;
else if (buf[i] == '1')
bitcnt[1][i]++;
else {
rlen = i;
break;
}
}
}
for (size_t i = 0; i < rlen; i++) {
if (bitcnt[0][i] < bitcnt[1][i])
gamma ^= 1 << (rlen - i - 1);
else
epsilon ^= 1 << (rlen - i - 1);
}
printf("Answer: %lu\n", gamma * epsilon);
}