diff options
author | kartofen <mladenovnasko0@gmail.com> | 2022-12-04 10:08:26 +0200 |
---|---|---|
committer | kartofen <mladenovnasko0@gmail.com> | 2022-12-04 10:08:26 +0200 |
commit | 9aee75494d8d2f025b193dfd582c2adca1a08e98 (patch) | |
tree | 136fc785c30a899111724f975a95fbf510f63a3d /Advent-of-Code-2022/aoc-4/main.c | |
parent | c438b26e7453d890d77c382d8737b74b96f7ac63 (diff) |
day 4
Diffstat (limited to 'Advent-of-Code-2022/aoc-4/main.c')
-rw-r--r-- | Advent-of-Code-2022/aoc-4/main.c | 76 |
1 files changed, 76 insertions, 0 deletions
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 <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <assert.h> + +#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; +} |