89 lines
1.9 KiB
C
89 lines
1.9 KiB
C
|
#define _GNU_SOURCE
|
||
|
#include <stdio.h>
|
||
|
#include <stdlib.h>
|
||
|
#include <string.h>
|
||
|
#include <stdint.h>
|
||
|
#include <stdbool.h>
|
||
|
|
||
|
|
||
|
// parse_number takes a position of a last digit in a number
|
||
|
// and returns a resulting number.
|
||
|
int32_t parse_number(char *end);
|
||
|
|
||
|
|
||
|
#define STR_E(tok) #tok
|
||
|
#define STR(tok) STR_E(tok)
|
||
|
|
||
|
|
||
|
#define SETS_STR_MAX_LEN 200
|
||
|
|
||
|
|
||
|
#define CUBE_RED_MAX 12
|
||
|
#define CUBE_GREEN_MAX 13
|
||
|
#define CUBE_BLUE_MAX 14
|
||
|
|
||
|
|
||
|
int main(int argc, char **argv) {
|
||
|
FILE *input;
|
||
|
char *line = NULL;
|
||
|
size_t line_length = 0;
|
||
|
|
||
|
if (argc == 1 || argv[1][0] == '-')
|
||
|
input = stdin;
|
||
|
else if ((input = fopen(argv[1], "r")) == NULL) {
|
||
|
printf("Cannot open file %s\n", argv[1]);
|
||
|
return -1;
|
||
|
}
|
||
|
|
||
|
int32_t game_id_sum = 0;
|
||
|
|
||
|
while (getline(&line, &line_length, input) != -1) {
|
||
|
char *colon_pos = strchr(line, ':');
|
||
|
|
||
|
int32_t game_id = parse_number(colon_pos - 1);
|
||
|
bool is_correct = true;
|
||
|
|
||
|
char *sets = colon_pos + 2;
|
||
|
char *space_pos = NULL;
|
||
|
|
||
|
while (NULL != (space_pos = strchr(sets, ' '))) {
|
||
|
if (*(space_pos-1) == ',' || *(space_pos-1) == ';') {
|
||
|
sets = space_pos + 1;
|
||
|
continue;
|
||
|
}
|
||
|
|
||
|
int8_t n = parse_number(space_pos-1);
|
||
|
|
||
|
if (('r' == *(space_pos+1) && CUBE_RED_MAX < n) ||
|
||
|
('g' == *(space_pos+1) && CUBE_GREEN_MAX < n) ||
|
||
|
('b' == *(space_pos+1) && CUBE_BLUE_MAX < n)) {
|
||
|
is_correct = false;
|
||
|
break;
|
||
|
}
|
||
|
|
||
|
sets = space_pos + 1;
|
||
|
}
|
||
|
|
||
|
if (is_correct)
|
||
|
game_id_sum += game_id;
|
||
|
|
||
|
memset(line, 0, line_length);
|
||
|
}
|
||
|
|
||
|
printf("%d\n", game_id_sum);
|
||
|
|
||
|
return 0;
|
||
|
}
|
||
|
|
||
|
int32_t parse_number(char *end) {
|
||
|
int32_t num = 0;
|
||
|
|
||
|
for (size_t n = 1;; n *= 10) {
|
||
|
if (*end>>4 != 0x3)
|
||
|
break;
|
||
|
num += (*end&0xf) * n;
|
||
|
--end;
|
||
|
}
|
||
|
|
||
|
return num;
|
||
|
}
|