#include #include #include #include #if 0 #define PART part1 #else #define PART part2 #endif #if 0 #define FILENAME "sample.txt" #else #define FILENAME "input.txt" #endif int res = 0; void part1(int *longer, int *shorter) { if(longer[0] <= shorter[0] && longer[1] >= shorter[1]) res++; } void part2(int *longer, int *shorter) { if((shorter[0] >= longer[0] && shorter[0] <= longer[1]) || (shorter[1] >= longer[0] && shorter[1] <= longer[1])) res++; } void parse() { FILE *fp = fopen(FILENAME, "r"); if(!fp) { fprintf(stderr, "ERROR: Could not open file: %s\n", FILENAME); exit(1); } char line[256]; while(fgets(line, sizeof(line), fp)) { int range1[2]; int range2[2]; char *r1 = strtok(line, ","); char *r2 = strtok(NULL, ","); assert(strtok(NULL, ",") == NULL); range1[0] = atoi(strtok(r1, "-")); range1[1] = atoi(strtok(NULL, "-")); assert(strtok(NULL, "-") == NULL); range2[0] = atoi(strtok(r2, "-")); range2[1] = atoi(strtok(NULL, "-")); assert(strtok(NULL, "-") == NULL); int len1 = range1[1] - range1[0] + 1; int len2 = range2[1] - range2[0] + 1; int *longer = (len1 > len2) ? range1 : range2; int *shorter = (len1 > len2) ? range2 : range1; PART(longer, shorter); } fclose(fp); } int main(void) { parse(); printf("%d\n", res); return 0; }