#include #include #include // 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; FILE *input; input = fopen("./input", "r"); nextGame: // 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; // change each ; to \0 while(ptr = strchr(ptr, ';')) { ptr[0] = '\0'; gameHands++; ptr++; } // for each 'hand' (semicolon) ((NULL-char)) for(gameHands; gameHands > 0; gameHands--) { // 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) gameCubes[i] = getCubes(ptr); // higher than colors[i]? jump to next game if (gameCubes[i] > cubes[i]) { goto nextGame; } } // pointer = strstr \0 + 1 offset += strlen(&row[offset]) + 1; ptr = row + offset; } // hit \n? add game ID to sum printf("Game %d valid\n", gameID); gameSum += gameID; } printf("Game ID sum: %d\n", gameSum); } 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; }