day 25 solved in C
[aoc_eblake.git] / 2018 / day8.c
blob87f30cb859b4a0ae36be1908ee911cf7438c2e74
1 #define _GNU_SOURCE 1
2 #include <stdio.h>
3 #include <string.h>
4 #include <stdlib.h>
5 #include <stdarg.h>
6 #include <stdbool.h>
8 void debug(const char *fmt, ...) {
9 va_list ap;
10 if (getenv("DEBUG")) {
11 va_start(ap, fmt);
12 vfprintf(stderr, fmt, ap);
13 va_end(ap);
17 typedef struct node node;
18 struct node {
19 char n_children;
20 char n_data;
21 node *children;
22 char *data;
23 int value;
25 static node head;
26 static int count;
27 static int sum;
29 void process(FILE *f, node *n) {
30 int i;
31 count++;
32 n->value = 0;
33 if (fscanf(f, "%hhd %hhd ", &n->n_children, &n->n_data) != 2) {
34 fprintf(stderr, "unexpected input\n");
35 exit(1);
37 if (!(n->children = malloc(n->n_children * sizeof(node))) ||
38 !(n->data = malloc(n->n_data))) {
39 perror("malloc");
40 exit(1);
42 for (i = 0; i < n->n_children; i++)
43 process(f, &n->children[i]);
44 for (i = 0; i < n->n_data; i++) {
45 if (fscanf(f, "%hhd ", &n->data[i]) != 1) {
46 fprintf(stderr, "unexpected input\n");
47 exit(1);
49 sum += n->data[i];
50 if (n->n_children) {
51 if (n->data[i] - 1U < n->n_children)
52 n->value += n->children[n->data[i] - 1].value;
53 } else
54 n->value += n->data[i];
58 int main(int argc, char **argv) {
59 if (argc > 1)
60 if (!(stdin = freopen(argv[1], "r", stdin))) {
61 perror("failure");
62 exit(2);
65 process(stdin, &head);
66 printf("read %d nodes, metadata sum %d\n", count, sum);
67 printf("root value %d\n", head.value);
68 return 0;