advent-of-code

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

a.c (1311B)


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

#define UNIQ_CHARS 14

/*
 * Tests if first UNIQ_CHARS chars of buf are all different.
 * Returns 1 if there is at least one common char, 0 if none.
 */
int
test_common(char *buf) {
    int common = 0;

    for (int i = 0; i < UNIQ_CHARS - 1; i++) {
        for (int j = i + 1; j < UNIQ_CHARS; j++) {
            if (buf[i] == buf[j]) {
                common = 1;
                goto done;
            }
        }
    }

done:
    return common;
}

int
main(int argc, char **argv) {
    char *buf = NULL;
    size_t buflen = 0;
    ssize_t n;
    FILE *f;

    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) {
        int i, solution = -1;
        if (buf[n - 1] == '\n') {
            buf[n - 1] = '\0';
            n--;
        }
        for (i = 0; i < n - UNIQ_CHARS - 1; i++) {
            if (test_common(&buf[i]) == 0) {
                solution = i + UNIQ_CHARS;
                break;
            }
        }
        if (solution != -1) {
            printf("%d\n", solution);
            break;
        }
    }

    free(buf);
    fclose(f);

    return 0;
}