aoc

My solutions for the Advent of Code
git clone https://git.tronto.net/aoc
Download | Log | Files | Refs | README

13b.c (1089B)


      1 #include <inttypes.h>
      2 #include <stdio.h>
      3 #include <string.h>
      4 
      5 #define N 64
      6 
      7 #define MAX(a,b) ((a)>(b)?(a):(b))
      8 
      9 char *buf, line[N];
     10 int64_t i, s, nc, nr, r[N], c[N];
     11 
     12 int64_t onebit(int64_t x) {
     13 	while (x % 2 == 0) x >>= 1;
     14 	return !(x-1);
     15 }
     16 
     17 int64_t issmudgedmirror(int64_t i, int64_t a[], int64_t n) {
     18 	int64_t smudge = 0;
     19 	for (int64_t j = MAX(0, 2*i-n+2); j <= i && 2*i-j+1 < n; j++) {
     20 		if (a[j] == a[2*i-j+1]) continue;
     21 		if (onebit(a[j] ^ a[2*i-j+1]))
     22 			smudge++;
     23 		else
     24 			return 0;
     25 	}
     26 	return smudge == 1;
     27 }
     28 
     29 int main() {
     30 	do {
     31 		buf = fgets(line, N, stdin);
     32 		if (buf == NULL || line[0] == '\n') {
     33 			for (i = 0; i < nc-1; i++)
     34 				s += (i + 1) * issmudgedmirror(i, c, nc);
     35 			for (i = 0; i < nr-1; i++)
     36 				s += 100 * (i + 1) * issmudgedmirror(i, r, nr);
     37 			nr = nc = 0;
     38 			memset(r, 0, N * sizeof(int64_t));
     39 			memset(c, 0, N * sizeof(int64_t));
     40 		} else {
     41 			for (nc = 0; line[nc] != '\n'; nc++) {
     42 				r[nr] = (r[nr] << 1) + (line[nc] == '#');
     43 				c[nc] = (c[nc] << 1) + (line[nc] == '#');
     44 			}
     45 			nr++;
     46 		}
     47 	} while (buf != NULL);
     48 
     49 	printf("%" PRId64 "\n", s);
     50 	return 0;
     51 }