day 1 more robust
[aoc_eblake.git] / 2016 / advent20.c
blobcea34b3ab9c07c14ddca5cedb943819ca05cb5d1
1 #define _GNU_SOURCE 1
2 #include <stdio.h>
3 #include <string.h>
4 #include <stdlib.h>
5 #include <unistd.h>
6 #include <stdbool.h>
7 #include <ctype.h>
9 #define MAX 1200 // cheat, by using wc on input file
10 typedef struct entry entry;
11 struct entry {
12 unsigned int lo;
13 unsigned int hi;
15 entry list[MAX];
17 int
18 compare (const void *a, const void *b)
20 const entry *e1 = a, *e2 = b;
21 return e1->lo < e2->lo ? -1 : e1->lo > e2->lo;
24 int
25 main (int argc, char **argv)
27 int count = 0;
28 unsigned int lo, hi;
29 while (scanf ("%d-%d\n", &lo, &hi) == 2) {
30 list[count].lo = lo;
31 list[count].hi = hi;
32 count++;
34 qsort (list, count, sizeof *list, compare);
35 printf ("read and sorted %d entries\n", count);
36 unsigned int min = 0;
37 unsigned int total = 0;
38 for (int i = 0; i < count; i++) {
39 if (min < list[i].lo) {
40 total += list[i].lo - min;
41 min = list[i].lo;
43 if (list[i].lo <= min && list[i].hi >= min) {
44 min = list[i].hi + 1;
45 if (!min)
46 break;
49 if (list[count - 1].hi < -1U)
50 total -= min;
51 printf ("total %u\n", total);
52 return 0;