From 31129c5916f428aa53d70530bea5b3765d066b52 Mon Sep 17 00:00:00 2001 From: Evan Burkey Date: Tue, 5 Dec 2023 21:59:01 -0800 Subject: [PATCH] 2023-02 --- include/advent_utility.h | 3 ++ src/2023/02.c | 62 +++++++++++++++++++++++++++++++++++++--- src/advent_utility.c | 3 +- 3 files changed, 63 insertions(+), 5 deletions(-) diff --git a/include/advent_utility.h b/include/advent_utility.h index 93c84e7..a84ed04 100644 --- a/include/advent_utility.h +++ b/include/advent_utility.h @@ -5,6 +5,9 @@ #define DEFAULT_DELIM " \t\n\r\f\v" +#define MAX(x, y) (x) > (y) ? (x) : (y) +#define MIN(x, y) (x) < (y) ? (x) : (y) + char *md5_str(const char *); char *capture_system(const char *); diff --git a/src/2023/02.c b/src/2023/02.c index 2b45a32..eab5eac 100644 --- a/src/2023/02.c +++ b/src/2023/02.c @@ -1,10 +1,64 @@ #include -#include +#include #include "lfinput.h" +#include "advent_utility.h" + +struct Game { + int id; + int red_max; + int green_max; + int blue_max; +}; + +static void parse(char *input, struct Game *g) { + memset(g, 0, sizeof(struct Game)); + + sscanf(input, "Game %d:", &g->id); + const char *c = strchr(input, ':') + 1; + char cpy[1024]; + strcpy(cpy, c); + + char *token = strtok(cpy, ",;"); + while (token != NULL) { + int count; + char color[10]; + if (sscanf(token, "%d %9s", &count, color) == 2) { + if (strcmp(color, "red") == 0) { + g->red_max = MAX(count, g->red_max); + } else if (strcmp(color, "blue") == 0) { + g->blue_max = MAX(count, g->blue_max); + } else if (strcmp(color, "green") == 0) { + g->green_max = MAX(count, g->green_max); + } + } + + token = strtok(NULL, ",;"); + } +} + +#define RED 12 +#define GREEN 13 +#define BLUE 14 + +static int valid(struct Game *g) { + return g->green_max <= GREEN && g->red_max <= RED && g->blue_max <= BLUE; +} void advent2023day02(void) { - char *input = get_input("input/2023/02"); - printf("Solution for Day 02 of 2023 is not completed yet\n"); - free(input); + size_t sz = 0; + char **lines = get_lines("input/2023/02", &sz); + int p1 = 0, p2 = 0; + + for (size_t i = 0; i < sz; ++i) { + struct Game g; + parse(lines[i], &g); + if (valid(&g)) { + p1 += g.id; + } + p2 += g.red_max * g.blue_max * g.green_max; + } + + printf("%d\n%d\n", p1, p2); + del_lines(lines); } diff --git a/src/advent_utility.c b/src/advent_utility.c index c4b39bb..ae92d4f 100644 --- a/src/advent_utility.c +++ b/src/advent_utility.c @@ -60,4 +60,5 @@ Vector *string_to_int_vector(const char *input_string, const char* delim) { free(copy); return v; -} \ No newline at end of file +} +