Files
advent-of-code-2023/day_2.c

87 lines
2.3 KiB
C

//
// Created by Lennart on 02/12/2023.
//
#define __STDC_WANT_LIB_EXT1__ 1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <stdbool.h>
#include "input_handler.h"
char *buffer;
int bufferLen;
#define MAX_RED_CUBES 12
#define MAX_GREEN_CUBES 13
#define MAX_BLUE_CUBES 14
#ifdef _WIN32
#define STRTOK_TS strtok_s
#elif defined(__STDC_LIB_EXT1__)
#define STRTOK_TS strtok_s
#elif _SVID_SOURCE || _BSD_SOURCE || _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _POSIX_SOURCE
#define STRTOK_TS strtok_r
#endif //_WIN32
void main() {
buffer = NULL;
FILE *f = fopen("day_2.txt", "r");
if(f == NULL) {
printf("File not found!");
exit(-1);
}
int result1 = 0;
int result2 = 0;
while(!feof(f)) {
char *line = read_line(f, &buffer, &bufferLen);
int gameId;
sscanf(line, "Game %i: ", &gameId);
char *sets = &line[strlen("Game : ") + (int) floor(log10(abs(gameId))) + 1];
char *set_context;
char *set = STRTOK_TS(sets, ";", &set_context);
int maxRed = 0, maxGreen = 0, maxBlue = 0;
bool fits = true;
while(set != NULL) {
char *cube = strtok(set, ",");
int red = 0, green = 0, blue = 0;
while(cube != NULL) {
int amount;
char color[10];
sscanf(cube, "%i %s", &amount, &color[0]);
if(strcmp(&color[0], "red") == 0 && (red += amount) > MAX_RED_CUBES) {
fits = false;
} else if(strcmp(&color[0], "green") == 0 && (green += amount) > MAX_GREEN_CUBES) {
fits = false;
} else if(strcmp(&color[0], "blue") == 0 && (blue += amount) > MAX_BLUE_CUBES) {
fits = false;
}
cube = strtok(NULL, ",");
}
maxRed = red > maxRed ? red : maxRed;
maxGreen = green > maxGreen ? green : maxGreen;
maxBlue = blue > maxBlue ? blue : maxBlue;
set = STRTOK_TS(NULL, ";", &set_context);
free(cube);
}
result1 += fits ? gameId : 0;
result2 += maxRed * maxGreen * maxBlue;
}
printf("Result #1: %i\n", result1);
printf("Result #2: %i\n", result2);
fclose(f);
free(buffer);
}