From 3e7812b55651ca18511d72ebd39a563f5e8b0f98 Mon Sep 17 00:00:00 2001 From: Duy Truong Date: Sat, 2 Dec 2023 00:08:03 -0800 Subject: [PATCH] fix d2p1 to be shorter --- 02/part1.c | 35 ++++++++++++++++------------------- 1 file changed, 16 insertions(+), 19 deletions(-) diff --git a/02/part1.c b/02/part1.c index 787e5e0..87b895d 100644 --- a/02/part1.c +++ b/02/part1.c @@ -1,27 +1,23 @@ #include #include #define MAX_LENGTH 165 -#define RED 1 -#define GREEN 2 -#define BLUE 3 -int strtocolor(char* c, char** end) { - if (c[0] == 'r' && c[1] == 'e' && c[2] == 'd') { - *end = c + 3; - return RED; - } else if (c[0] == 'g' && c[1] == 'r' && c[2] == 'e' && c[3] == 'e' && c[4] == 'n') { - *end = c + 5; - return GREEN; - } else if (c[0] == 'b' && c[1] == 'l' && c[2] == 'u' && c[3] == 'e') { - *end = c + 4; - return BLUE; +char* skip_color(char* c) { + switch (*c) { + case 'r': + return c + 3; + case 'g': + return c + 5; + case 'b': + return c + 4; } abort(); } + int main(void) { char buf[MAX_LENGTH]; - int game_num, color_num, color, sum; + int game_num, cubes, sum; sum = 0; while (fgets(buf, MAX_LENGTH, stdin)) { @@ -29,13 +25,14 @@ int main(void) { game_num = strtol(c + 5, &c, 10); // +5 skips the "Game " while (*c != '\n') { - color_num = strtol(c + 2, &c, 10); // +2 skips ": ", ", ", or "; " - color = strtocolor(c + 1, &c); // +1 skips the space - if ((color == RED && color_num > 12) || - (color == GREEN && color_num > 13) || - (color == BLUE && color_num > 14)) { + cubes = strtol(c + 2, &c, 10); // +2 skips ": ", ", ", or "; " + c++; // +1 skips the space + if ((*c == 'r' && cubes > 12) || + (*c == 'g' && cubes > 13) || + (*c == 'b' && cubes > 14)) { game_num = 0; } + c = skip_color(c); } sum += game_num; }