~cdv/aoc-2018-c

9ec032d01b0cfafbd2b1d18d445ed375a18470e3 — Christopher Vittal 1 year, 3 months ago 7fee42c
Solve day 9
3 files changed, 82 insertions(+), 2 deletions(-)

A data/day09
M src/day09.c
M src/main.c
A data/day09 => data/day09 +1 -0
@@ 0,0 1,1 @@
424 players; last marble is worth 71144 points

M src/day09.c => src/day09.c +79 -1
@@ 1,3 1,81 @@
#include <stdbool.h>
#include <stdio.h>
void solve_day09(bool part2, FILE *in, FILE *out) {}
#include <stdlib.h>

struct node {
	size_t item;
	struct node *next, *prev;
};

typedef struct node* list;

list init_list(size_t item) {
	list l = malloc(sizeof(struct node));
	if (l != NULL) {
		l->item = item;
		l->next = l;
		l->prev = l;
	}
	return l;
}

list list_insert(list lst, size_t item) {
	list new = malloc(sizeof(struct node));
	if (new != NULL) {
		new->item = item;
		list pre = lst->prev;
		lst->prev = new;
		pre->next = new;
		new->prev = pre;
		new->next = lst;
	}
	return new;
}

list list_erase(list l) {
	l->next->prev = l->prev;
	l->prev->next = l->next;
	list ret = l->next;
	free(l);
	return ret;
}

void list_free(list l) {
	if (l == NULL)
		return;
	list n = l->next;
	free(l);
	while (n != l) {
		list t = n->next;
		free(n);
		n = t;
	}
}

void solve_day09(bool part2, FILE *in, FILE *out) {
	int players, marbles;
	fscanf(in, "%d players; last marble is worth %d points", &players, &marbles);
	size_t *scores = calloc(players, sizeof(size_t));
	list l = init_list(0);
	if (part2)
		marbles *= 100;

	for (int i = 1; i <= marbles; ++i) {
		if (i % 23 == 0) {
			l = l->prev->prev->prev->prev->prev->prev->prev;
			scores[i % players] += i + l->item;
			l = list_erase(l);
		} else {
			l = l->next->next;
			l = list_insert(l, i);
		}
	}

	size_t max = 0;
	for (int i = 0; i < players; ++i)
		max = scores[i] > max ? scores[i] : max;
	fprintf(out, "  %d: %lu\n", part2 ? 2 : 1, max);

	list_free(l);
	free(scores);
}

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

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

typedef struct {
	bool part1, part2, time;


@@ 40,6 40,7 @@ int main(int argc, char** argv) {
		if (opt.part1) { run(d, false, opt.time, out); }
		if (opt.part2) { run(d, true,  opt.time, out); }
	}
	regfree(&opt.filter);
}

void run(Day day, bool part2, bool time, FILE* out) {