summaryrefslogtreecommitdiff
path: root/Advent-of-Code-2022/aoc-4/main.c
blob: 56dfcfd181b00e0096ec799ebf615de08d22b975 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
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;
}