puzzle.c (1738B)
1 #define _DEFAULT_SOURCE 2 3 #include <limits.h> 4 #include <stdio.h> 5 #include <stdlib.h> 6 #include <errno.h> 7 #include <string.h> 8 #include <strings.h> 9 #include <assert.h> 10 #include <stdbool.h> 11 12 #define STR_LEN 2048 13 14 bool is_digit(char b) { 15 return b>='0' && b<='9'; 16 } 17 18 void puzzle(const char *filename, long long *result1, long long *result2) { 19 FILE *infile = fopen(filename, "r"); 20 if (infile == NULL) { 21 fprintf(stderr, "fopen() error: %s\n", strerror(errno)); 22 return; 23 } 24 25 char buf[STR_LEN] = {0}; 26 unsigned int line_num = 0; 27 28 *result1 = 0; 29 *result2 = 0; 30 31 while (fgets(buf, STR_LEN, infile) != NULL) { 32 int game_num; 33 int n = sscanf(buf, "Game %d:", &game_num); 34 if (n==1) { 35 //printf("game %d\n", game_num); 36 } else { 37 printf("parse error\n"); 38 break; 39 } 40 41 char *game_sep = strpbrk(buf, ":"); 42 if (game_sep==NULL) { 43 printf("delim parse error\n"); 44 break; 45 } 46 47 bool game_valid = true; 48 int len = strlen(game_sep); 49 int i = 0; 50 int r=0,g=0,b=0; 51 while (i<len) { 52 if (is_digit(game_sep[i])) { 53 int number = game_sep[i]-'0'; 54 if (is_digit(game_sep[i+1])) { 55 number = number*10 + (game_sep[i+1]-'0'); 56 ++i; 57 } 58 char color = game_sep[i+2]; 59 //printf("%d %c\n", number, color); 60 61 if (color=='r') { 62 if (number>12) game_valid = false; 63 if (number>r) r = number; 64 } 65 if (color=='g') { 66 if (number>13) game_valid = false; 67 if (number>g) g = number; 68 } 69 if (color=='b') { 70 if (number>14) game_valid = false; 71 if (number>b) b = number; 72 } 73 } 74 ++i; 75 } 76 77 if (game_valid) { 78 *result1 += game_num; 79 } 80 81 *result2 += r*g*b; 82 83 ++line_num; 84 bzero(buf, STR_LEN); 85 } 86 87 // mutiny! ignoring feof/ferror. 88 fclose(infile); 89 90 (void)result1; 91 (void)result2; 92 }