aoc

Advent of code
git clone https://codeberg.org/night0721/aoc
Log | Files | Refs

2.c (1983B)


      1 #include "../../util.h"
      2 
      3 #include <stdio.h>
      4 #include <string.h>
      5 #include <stdlib.h>
      6 #include <assert.h>
      7 #include <ctype.h>
      8 
      9 typedef struct {
     10     int id;
     11     int colors[3];
     12 } game;
     13 
     14 int main() {
     15     FILE *inputfile = fopen("./input", "r");
     16     char line[1024] = { 0 };
     17     int sum = 0;
     18     size_t len = 0;
     19     ssize_t read;
     20     if (inputfile == NULL) {
     21         printf("Input file not found. Exiting.");
     22         exit(1);
     23     }
     24     while (fgets(line, 1024, inputfile)) {
     25         int colors[3] = { 0, 0, 0 };
     26         line[strcspn(line, "\n")] = 0;
     27         char **splitted = str_split(line, ':');
     28         char *id = str_split(splitted[0], ' ')[1];
     29         char **sets = str_split(splitted[1], ';');
     30         int maxes[3] = { 0, 0, 0 };
     31         for (int i = 0; sets[i]; i++) {
     32             int colors[3] = { 0, 0, 0 };
     33             sets[i] = trimwhitespace(sets[i]);
     34             char **subset = str_split(sets[i], ',');
     35             for (int j = 0; subset[j]; j++) {
     36                 subset[j] = trimwhitespace(subset[j]);
     37                 char **splittedsubset = str_split(subset[j], ' ');
     38                 char *count = splittedsubset[0];
     39                 char *color = splittedsubset[1];
     40                 if (strncmp(color, "red", 3) == 0) {
     41                     colors[0] = atoi(count);
     42                 } else if (strncmp(color, "green", 5) == 0) {
     43                     colors[1] = atoi(count);
     44                 } else if (strncmp(color, "blue", 4) == 0) {
     45                     colors[2] = atoi(count);
     46                 }
     47                 if (colors[0] > maxes[0]) {
     48                     maxes[0] = colors[0];
     49                 }
     50                 if (colors[1] > maxes[1]) {
     51                     maxes[1] = colors[1];
     52                 }
     53                 if (colors[2] > maxes[2]) {
     54                     maxes[2] = colors[2];
     55                 }
     56             }
     57         }
     58         sum += maxes[0] * maxes[1] * maxes[2];
     59         free(splitted);
     60     }
     61     fclose(inputfile);
     62     printf("%d\n", sum);
     63     return 0;
     64 }