From 9aee75494d8d2f025b193dfd582c2adca1a08e98 Mon Sep 17 00:00:00 2001 From: kartofen Date: Sun, 4 Dec 2022 10:08:26 +0200 Subject: day 4 --- Advent-of-Code-2022/aoc-4/main.c | 76 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 Advent-of-Code-2022/aoc-4/main.c (limited to 'Advent-of-Code-2022/aoc-4/main.c') diff --git a/Advent-of-Code-2022/aoc-4/main.c b/Advent-of-Code-2022/aoc-4/main.c new file mode 100644 index 0000000..56dfcfd --- /dev/null +++ b/Advent-of-Code-2022/aoc-4/main.c @@ -0,0 +1,76 @@ +#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; +} -- cgit v1.2.3