aoc

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

3b.c (1247B)


      1 #include <stdio.h>
      2 #include <stdlib.h>
      3 #include <string.h>
      4 
      5 #define N 1000
      6 #define ISNUM(c) (c >= '0' && c <= '9')
      7 
      8 int grab(char *buf) {
      9 	if (!ISNUM(*buf)) return 0;
     10 	while (ISNUM(*buf)) buf--;
     11 	buf++;
     12 	int x = atoi(buf);
     13 	while (ISNUM(*buf)) *buf++ = '.';
     14 
     15 	return x;
     16 }
     17 
     18 void push(int *j, int *g, char *buf) {
     19 	g[*j] = grab(buf);
     20 	if (g[*j] > 0) (*j)++;
     21 }
     22 
     23 int main() {
     24 	char *cont, line[N], prev[N], next[N], backup[3][N];
     25 	int i, sum, j, g[9];
     26 
     27 	sum = 0;
     28 	memset(line, '.', N);
     29 	memset(prev, '.', N);
     30 	memset(next, '.', N);
     31 	cont = fgets(&next[1], N-1, stdin);
     32 	while (cont != NULL) {
     33 		memcpy(line, next, N);
     34 		cont = fgets(&next[1], N-1, stdin);
     35 		for (i = 1; line[i]; i++) {
     36 			if (line[i] == '*') {
     37 				memcpy(backup[0], prev, N);
     38 				memcpy(backup[1], line, N);
     39 				memcpy(backup[2], next, N);
     40 				j = 0;
     41 				push(&j, g, &prev[i-1]);
     42 				push(&j, g, &prev[i]);
     43 				push(&j, g, &prev[i+1]);
     44 				push(&j, g, &line[i-1]);
     45 				push(&j, g, &line[i+1]);
     46 				push(&j, g, &next[i-1]);
     47 				push(&j, g, &next[i]);
     48 				push(&j, g, &next[i+1]);
     49 				if (j == 2) sum += g[0] * g[1];
     50 				memcpy(prev, backup[0], N);
     51 				memcpy(line, backup[1], N);
     52 				memcpy(next, backup[2], N);
     53 			}
     54 		}
     55 		memcpy(prev, line, N);
     56 	}
     57 
     58 	printf("%d\n", sum);
     59 	return 0;
     60 }