advent-of-code

advent of code attempts
git clone git://bvnf.space/advent-of-code.git
Log | Files | Refs

a.c (1217B)


      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
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>

struct pair {
    int min, max;
};

int
main(int argc, char **argv) {
    char *buf = NULL;
    size_t buflen = 0;
    ssize_t n;
    FILE *f;
    struct pair p[2] = {0};
    int part_a = 0, part_b = 0;

    if (argc != 2) {
        fprintf(stderr, "usage: %s input\n", argv[0]);
        return 1;
    }

    f = fopen(argv[1], "r");
    if (f == NULL) {
        perror(argv[1]);
        return 1;
    }

    while ((n = getline(&buf, &buflen, f)) != -1) {
        if (buf[n - 1] == '\n') {
            buf[n - 1] = '\0';
            n--;
        }
        if (4 != sscanf(buf, "%d-%d,%d-%d", &p[0].min, &p[0].max, &p[1].min, &p[1].max)) {
            perror("sscanf");
            return 1;
        }
        if ((p[0].min <= p[1].min && p[0].max >= p[1].max) ||
            (p[1].min <= p[0].min && p[1].max >= p[0].max)) {
            part_a++;
            part_b++;
        } else if ((p[0].min <= p[1].min && p[0].max >= p[1].min) ||
            (p[1].min <= p[0].min && p[1].max >= p[0].min)) {
            part_b++;
        }
    }
    printf("PART A: %d\n", part_a);
    printf("PART B: %d\n", part_b);
    free(buf);
    fclose(f);
    return 0;
}