aoc

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

3a.c (816B)


      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 #define ISSYM(c) (c != '.' && c != 0 && c != '\n' && !ISNUM(c))
      8 
      9 int grab(char *buf) {
     10 	if (!ISNUM(*buf)) return 0;
     11 	while (ISNUM(*buf)) buf--;
     12 	buf++;
     13 	int x = atoi(buf);
     14 	while (ISNUM(*buf)) *buf++ = '.';
     15 
     16 	return x;
     17 }
     18 
     19 int main() {
     20 	char line[N], prev[N];
     21 	int i, sum;
     22 
     23 	sum = 0;
     24 	memset(line, '.', N);
     25 	memset(prev, '.', N);
     26 	while (fgets(&line[1], N-1, stdin) != NULL) {
     27 		for (i = 1; line[i]; i++) {
     28 			if (ISSYM(line[i-1]) || ISSYM(line[i+1]) ||
     29 			    ISSYM(prev[i-1]) || ISSYM(prev[i]) || ISSYM(prev[i+1]))
     30 				sum += grab(&line[i]);
     31 			if (ISSYM(line[i-1]) || ISSYM(line[i]) || ISSYM(line[i+1]))
     32 				sum += grab(&prev[i]);
     33 		}
     34 		memcpy(prev, line, N);
     35 	}
     36 
     37 	printf("%d\n", sum);
     38 	return 0;
     39 }