puzzle.c (1642B)
1 #define _DEFAULT_SOURCE 2 3 #include <limits.h> 4 #include <stdint.h> 5 #include <stdio.h> 6 #include <stdlib.h> 7 #include <errno.h> 8 #include <string.h> 9 #include <strings.h> 10 #include <assert.h> 11 #include <stdbool.h> 12 13 #define STR_LEN 2048 14 15 bool is_digit(char b) { 16 return b>='0' && b<='9'; 17 } 18 19 // I'll skip the parse part for now 20 21 typedef struct Race { 22 int time; 23 int record; 24 } Race; 25 26 void puzzle(const char *filename, long long *result1, long long *result2) { 27 FILE *infile = fopen(filename, "r"); 28 if (infile == NULL) { 29 fprintf(stderr, "fopen() error: %s\n", strerror(errno)); 30 return; 31 } 32 33 char buf[STR_LEN] = {0}; 34 unsigned int line_num = 0; 35 36 *result1 = 0; 37 *result2 = 0; 38 39 while (fgets(buf, STR_LEN, infile) != NULL) { 40 41 ++line_num; 42 bzero(buf, STR_LEN); 43 } 44 45 // test data 46 /*Race races[3] = { 47 { .time = 7, .record = 9 }, 48 { .time = 15, .record = 40 }, 49 { .time = 30, .record = 200 } 50 };*/ 51 52 // real data 53 Race races[4] = { 54 { .time = 45, .record = 305 }, 55 { .time = 97, .record = 1062 }, 56 { .time = 72, .record = 1110 }, 57 { .time = 95, .record = 1695 }, 58 }; 59 60 *result1 = 1; 61 for (int i=0; i<4; ++i) { 62 int wins = 0; 63 for (int t=1; t<races[i].time; ++t) { // holding the button 64 int speed = t; 65 int time = races[i].time-t; 66 int dist = speed*time; 67 if (dist>races[i].record) wins++; 68 } 69 //printf("wins: %d\n", wins); 70 *result1 *= wins; 71 } 72 73 { 74 int wins = 0; 75 for (uint64_t t=1; t<45977295; ++t) { // holding the button 76 uint64_t speed = t; 77 uint64_t time = 45977295-t; 78 uint64_t dist = speed*time; 79 if (dist>305106211101695) wins++; 80 } 81 *result2 = wins; 82 } 83 84 // mutiny! ignoring feof/ferror. 85 fclose(infile); 86 }