aoc

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

9a.c (811B)


      1 #include <inttypes.h>
      2 #include <stdbool.h>
      3 #include <stdio.h>
      4 #include <stdlib.h>
      5 
      6 #define N 1000
      7 
      8 #define isnum(c) (c == '-' || (c >= '0' && c <= '9'))
      9 
     10 int64_t readl(int64_t nums[], char *buf) {
     11 	int64_t i;
     12 	for (i = 0; *buf; buf++) {
     13 		if (!isnum(*buf)) continue;
     14 		nums[i++] = atoll(buf);
     15 		while (isnum(*buf)) buf++;
     16 	}
     17 	return i;
     18 }
     19 
     20 bool isconstant(int64_t a[], int n) {
     21 	for (int i = 0; i < n-1; i++)
     22 		if (a[i] != a[i+1])
     23 			return false;
     24 	return true;
     25 }
     26 
     27 int64_t next(int64_t a[], int64_t n) {
     28 	int64_t x = a[n-1];
     29 	if (isconstant(a, n))
     30 		return x;
     31 	for (int i = 0; i < n-1; i++)
     32 		a[i] = a[i+1] - a[i];
     33 	return x + next(a, n-1);
     34 }
     35 
     36 int main() {
     37 	char line[N];
     38 	int64_t s, a[N];
     39 
     40 	for (s = 0; fgets(line, N, stdin) != NULL; )
     41 		s += next(a, readl(a, line));
     42 
     43 	printf("%" PRId64 "\n", s);
     44 	return 0;
     45 }