aoc

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

12a.c (1150B)


      1 #include <stdio.h>
      2 #include <stdlib.h>
      3 #include <string.h>
      4 
      5 #define N 1000
      6 
      7 #define ABS(a) ((a)>0?(a):-(a))
      8 
      9 #define isnum(c) (c == '-' || (c >= '0' && c <= '9'))
     10 
     11 char *buf, line[N];
     12 int s, n, a[N];
     13 
     14 int readl(int nums[], char *buf) {
     15 	int i;
     16 	for (i = 0; *buf; buf++) {
     17 		if (!isnum(*buf)) continue;
     18 		nums[i++] = atoll(buf);
     19 		while (isnum(*buf)) buf++;
     20 	}
     21 	return i;
     22 }
     23 
     24 int isgood(char *line, int a[], int n) {
     25 	int b[N];
     26 	memset(b, 0, N * sizeof(int));
     27 	memcpy(b, a, n * sizeof(int));
     28 	for (int j = 0, c = 0; *line != ' '; line++) {
     29 		if (*line == '?') printf("Error!\n");
     30 		if (*line == '.') { j += c; c = 0; }
     31 		if (*line == '#') { c = 1; b[j]--; }
     32 	}
     33 	for (int j = 0; j < N; j++)
     34 		if (b[j])
     35 			return 0;
     36 	return 1;
     37 }
     38 
     39 int arrange(char *line, char *buf, int a[], int n) {
     40 	while (*buf != '?' && *buf != ' ') buf++;
     41 	if (*buf == ' ')
     42 		return isgood(line, a, n);
     43 	*buf = '.';
     44 	int x = arrange(line, buf, a, n);
     45 	*buf = '#';
     46 	int y = arrange(line, buf, a, n);
     47 	*buf = '?';
     48 	return x + y;
     49 }
     50 
     51 int main() {
     52 	while ((buf = fgets(line, N, stdin)) != NULL) {
     53 		n = readl(a, buf);
     54 		s += arrange(line, buf, a, n);
     55 	}
     56 
     57 	printf("%d\n", s);
     58 	return 0;
     59 }