~cdv/aoc-2018-c

7fee42c887520d1edbb7df74d045eca77d643098 — Christopher Vittal 1 year, 3 months ago e443627
Solve day 8
2 files changed, 72 insertions(+), 2 deletions(-)

M src/day08.c
M src/main.c
M src/day08.c => src/day08.c +71 -1
@@ 1,3 1,73 @@
#include "vector.h"

#include <stdbool.h>
#include <stdio.h>
void solve_day08(bool part2, FILE *in, FILE *out) {}

struct slice {
	const size_t *ptr;
	size_t len;
};

struct triple {
	struct slice data;
	size_t meta_sum, value;
};

static struct triple compute(struct slice data) {
	size_t nc = data.ptr[0];
	size_t nm = data.ptr[1];
	size_t meta_sum = 0;
	size_t children[nc];
	size_t clen = 0;

	data.ptr += 2;
	data.len -= 2;

	for (size_t i = 0; i < nc; ++i) {
		struct triple t = compute(data);
		data = t.data;
		meta_sum += t.meta_sum;
		children[clen++] = t.value;
	}

	struct slice md = {.ptr = data.ptr, .len = nm};
	size_t v = 0, value;
	for (const size_t *p = md.ptr; p != md.ptr+md.len; ++p)
		v += *p;
	meta_sum += v;
	if (nc == 0) {
		value = v;
	} else {
		size_t tmp = 0;
		for (const size_t *p = md.ptr; p != md.ptr+md.len; ++p)
			if (*p > 0 && *p <= clen)
				tmp += children[*p - 1];
		value = tmp;
	}

	struct triple ret = {
		.data = {.ptr=data.ptr+nm, .len=data.len-nm},
		.meta_sum = meta_sum,
		.value = value,
	};
	return ret;
}

void solve_day08(bool part2, FILE *in, FILE *out) {
	Vec data = vec_new();
	size_t n = 0;
	char *line = NULL;
	getline(&line, &n, in);
	char *p = line, *q = line;
	while (*q != '\0') {
		size_t n = strtoul(p, &q, 10);
		if (p == q) break;
		vec_push(&data, n);
		p = q;
	}
	struct slice s = {.ptr = data.ptr, .len=data.len};
	struct triple t = compute(s);
	fprintf(out, "  %d: %lu\n", part2 ? 2 : 1, part2 ? t.value : t.meta_sum);
	free(line);
	vec_free(data);
}

M src/main.c => src/main.c +1 -1
@@ 7,7 7,7 @@
#include <string.h>
#include <time.h>

#define NO_INPUT(day) ((day) > 3)
#define NO_INPUT(day) ((day) > 8)

typedef struct {
	bool part1, part2, time;