82 lines
2.1 KiB
C
82 lines
2.1 KiB
C
//
|
|
// Created by Lennart on 02/12/2023.
|
|
//
|
|
|
|
#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
|
|
#else
|
|
#define STRTOK_TS strtok_f
|
|
#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;
|
|
const char *set = STRTOK_TS(sets, ";", &set_context);
|
|
|
|
int maxRed = 0, maxGreen = 0, maxBlue = 0;
|
|
bool fits = true;
|
|
while(set != NULL) {
|
|
const 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);
|
|
}
|
|
|
|
result1 += fits ? gameId : 0;
|
|
result2 += maxRed * maxGreen * maxBlue;
|
|
}
|
|
|
|
printf("Result #1: %i\n", result1);
|
|
printf("Result #2: %i\n", result2);
|
|
|
|
fclose(f);
|
|
free(buffer);
|
|
}
|