Untitled
unknown
plain_text
2 years ago
1.8 kB
8
Indexable
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct CubeCount {
uint8_t r;
uint8_t g;
uint8_t b;
uint8_t gameID;
} CubeCount;
uint8_t checkGame(const CubeCount *const restrict totalCubes,
char *const restrict gameData) {
uint8_t result = 0;
char *gameNext = gameData;
char *gameToken = strtok_r(gameData, ":", &gameNext);
char *roundNext = NULL;
char *roundToken;
if (gameToken != NULL) {
sscanf(gameToken, "Game %hhu[3]:", &result);
}
gameToken = strtok_r(gameNext, ";", &gameNext);
while (gameToken != NULL) {
CubeCount round = {0};
roundToken = strtok_r(gameToken, ",", &roundNext);
while (roundToken != NULL) {
char color[6] = {0};
uint8_t val = 0;
sscanf(roundToken, "%hhu %s", &val, color);
if (strcmp(color, "red") == 0)
round.r = val;
if (strcmp(color, "green") == 0)
round.g = val;
if (strcmp(color, "blue") == 0)
round.b = val;
roundToken = strtok_r(roundNext, ",", &roundNext);
}
if (totalCubes->r < round.r || totalCubes->g < round.g ||
totalCubes->b < round.b)
result = 0;
gameToken = strtok_r(gameNext, ";", &gameNext);
}
return (uint8_t)result;
}
int main(int argc, char **argv) {
uint32_t successfulIdSum = 0;
char games[100][1024] = {0};
CubeCount totalCubes = {12, 13, 14, 0};
FILE *fp;
fp = fopen("./day2.input", "r");
if (fp == NULL) {
fprintf(stderr, "Failed to load input.\n");
return EXIT_FAILURE;
}
for (size_t i = 0; i < 100; i++) {
fscanf(fp, "%1024[^\n]\n", games[i]);
successfulIdSum += checkGame(&totalCubes, games[i]);
}
printf("Sum of successful game IDs: %u\n", successfulIdSum);
}Editor is loading...
Leave a Comment