#define _GNU_SOURCE #include #include #include #include #include uint64_t parse_number(char *end); #define SETS_STR_MAX_LEN 200 #define CUBE_RED 0 #define CUBE_GREEN 1 #define CUBE_BLUE 2 int main(int argc, char **argv) { FILE *input; char *line = NULL; size_t line_length = 0; if (argc == 1 || argv[1][0] == '-') input = stdin; else if ((input = fopen(argv[1], "r")) == NULL) { fprintf(stderr, "Cannot open file %s\n", argv[1]); return -1; } uint64_t power_sum = 0; while (getline(&line, &line_length, input) != -1) { char *colon_pos = strchr(line, ':'); char *sets = colon_pos + 2; char *space_pos = NULL; int8_t cubes[3] = {0}; while (NULL != (space_pos = strchr(sets, ' '))) { if (*(space_pos-1) == ',' || *(space_pos-1) == ';') { sets = space_pos + 1; continue; } uint8_t n = parse_number(space_pos-1); switch (*(space_pos+1)) { case 'r': if (cubes[CUBE_RED] < n) cubes[CUBE_RED] = n; break; case 'g': if (cubes[CUBE_GREEN] < n) cubes[CUBE_GREEN] = n; break; case 'b': if (cubes[CUBE_BLUE] < n) cubes[CUBE_BLUE] = n; break; } sets = space_pos + 1; } power_sum += cubes[CUBE_RED] * cubes[CUBE_GREEN] * cubes[CUBE_BLUE]; memset(line, 0, line_length); } printf("%lu\n", power_sum); return 0; } uint64_t parse_number(char *end) { uint64_t num = 0; for (size_t n = 1;; n *= 10) { if (*end>>4 != 0x3) break; num += (*end&0xf) * n; --end; } return num; }