AoC2023/day2/'

106 lines
2.4 KiB
Text

#include <stdio.h>
#include <string.h>
#include <limits.h>
#define MAX_GAMES 101
// cubes, R, G, B
const int cubes[3] = {12, 13, 14};
const char *colors[] = {"red", "green", "blue"};
int getCubes(char *ptr);
int main ()
{
int gameID = 0;
int gameSum = 0;
char row[160];
char *ptr;
int length = 0;
int gameCubes[3] = {0, 0, 0};
int gameHands = 0;
int offset = 0;
int game[MAX_GAMES] = {0};
for (int i = 1; i < MAX_GAMES; i++)
game[i] = i;
int powerSum = 0;
FILE *input;
input = fopen("./input", "r");
// for each row
while(fgets(row, 160, input) != NULL) {
// increment game count
gameID++;
gameHands = 1;
offset = 0;
for (int i = 0; i < 3; i++) gameCubes[i] = 0;
printf("%s\n", row);
// not neccesary to decide length when we know amount of ';'?
// length = strchr(row, '\n') - &row[0];
// change each ; to \0
ptr = row;
while(ptr = strchr(ptr, ';')) {
ptr[0] = '\0';
gameHands++;
ptr++;
}
printf("\nGame %d hands: %d\n", gameID, gameHands);
// for each 'hand' (semicolon) ((NULL-char))
for(gameHands; gameHands > 0; gameHands--) {
printf("%s\n", row + offset);
// for each color
for(int i = 0; i < 3; i++) {
// use strstr to find color,
// move pointer to the beginning of said colour
ptr = strstr(row + offset, colors[i]);
// if (strstr(row, colors[i]) != NULL)
if (ptr != NULL) {
if (gameCubes[i] < getCubes(ptr))
gameCubes[i] = getCubes(ptr);
}
// higher than colors[i]? invalidate the game
if (gameCubes[i] > cubes[i]) {
game[gameID] = 0;
// printf("Game %d invalid\n", gameID);
}
}
// pointer = strstr \0 + 1
offset += strlen(&row[offset]) + 1;
ptr = row + offset;
}
// printf("Game %d required RGB: %d, %d, %d\n",
// gameID, gameCubes[0],gameCubes[1],gameCubes[2]
// );
powerSum += gameCubes[0] * gameCubes[1] * gameCubes[2];
printf("Game %d powersum: %d\nCurrent Total: %d\n", gameID, gameCubes[0] * gameCubes[1] * gameCubes[2], powerSum);
}
for (int i = gameID + 1; i < MAX_GAMES; i++)
game[i] = 0;
for (int i = 0; i < MAX_GAMES; i++) {
gameSum += game[i];
}
printf("Game ID sum: %d\n", gameSum);
printf("Total power sum: %d\n", powerSum);
}
int getCubes(char *ptr)
{
int num = 0;
// get two chars: pointer -3, pointer -2
// convert them to an int
if (ptr[-3] >= '0' && ptr[-3] <= '9') {
num += (ptr[-3] - '0') * 10;
}
if (ptr[-2] >= '0' && ptr[-2] <= '9') {
num += ptr[-2] - '0';
}
return num;
}