From c6ed79ba6ae83ee7ec0d733199749513da5b296b Mon Sep 17 00:00:00 2001 From: mid-kid Date: Sun, 16 Dec 2018 15:06:01 +0100 Subject: [PATCH] day9p1 --- day9p1/Makefile | 12 +++++++ day9p1/input | 1 + day9p1/main.c | 89 +++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 102 insertions(+) create mode 100644 day9p1/Makefile create mode 100644 day9p1/input create mode 100644 day9p1/main.c diff --git a/day9p1/Makefile b/day9p1/Makefile new file mode 100644 index 0000000..5ad0e7f --- /dev/null +++ b/day9p1/Makefile @@ -0,0 +1,12 @@ +CFLAGS := -Wall -Wextra -std=c17 -D_GNU_SOURCE + +#LIBS := glib-2.0 +#CFLAGS += $(shell pkg-config --cflags $(LIBS)) +#LDLIBS := $(shell pkg-config --libs $(LIBS)) + +.PHONY: all +all: main + +.PHONY: clean +clean: + rm -f main diff --git a/day9p1/input b/day9p1/input new file mode 100644 index 0000000..486ce81 --- /dev/null +++ b/day9p1/input @@ -0,0 +1 @@ +447 players; last marble is worth 71510 points diff --git a/day9p1/main.c b/day9p1/main.c new file mode 100644 index 0000000..1c580b6 --- /dev/null +++ b/day9p1/main.c @@ -0,0 +1,89 @@ +#include +#include + +struct marble { + struct marble *next; + struct marble *prev; + int value; +}; + +void *xmalloc(size_t size) +{ + void *res = malloc(size); + if (!res) { + perror("malloc"); + exit(1); + } + return res; +} + +void *xcalloc(size_t nmemb, size_t size) +{ + void *res = calloc(nmemb, size); + if (!res) { + perror("calloc"); + exit(1); + } + return res; +} + +int main(int argc, char *argv[]) +{ + if (argc <= 2) { + fprintf(stderr, "Usage: %s \n", argv[0]); + return 1; + } + + int players = strtol(argv[1], NULL, 0); + int marbles = strtol(argv[2], NULL, 0); + if (!players || marbles <= 1) return 1; + + int *scores = xcalloc(players, sizeof(int)); + int player = 0; + + struct marble *current = xmalloc(sizeof(struct marble)); + current->next = current; + current->prev = current; + current->value = 0; + + for (int i = 1; i <= marbles; i++) { + if (i % 23 == 0) { + scores[player] += i; + for (int i = 0; i < 7; i++) { + current = current->prev; + } + scores[player] += current->value; + current->prev->next = current->next; + current->next->prev = current->prev; + + struct marble *remove = current; + current = current->next; + free(remove); + } else { + current = current->next; + struct marble *new = xmalloc(sizeof(struct marble)); + new->next = current->next; + new->prev = current; + new->next->prev = new; + new->prev->next = new; + new->value = i; + current = new; + } + + if (++player >= players) player = 0; + } + + int highest = 0; + for (int *score = scores; score < scores + players; score++) { + if (*score > highest) highest = *score; + } + printf("Highest score: %d\n", highest); + + current->prev->next = NULL; + while (current->next) { + current = current->next; + free(current->prev); + } + free(current); + return 0; +}