summaryrefslogtreecommitdiff
path: root/Advent-of-Code-2022/aoc-3/main.c
blob: d8e5815632097d5eb6da58e537fcbde008726fd7 (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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#if 0
  #define PART part1
#else
  #define PART part2
#endif

#if 0
  #define FILENAME "sample.txt"
#else
  #define FILENAME "input.txt"
#endif

int sum = 0;

int char_to_index(char ch)
{
    if(ch >= 'a')
        return ch - 'a';
    return ch - 'A' + 26;
}

void part1(char *line)
{
    int times_seen[56] = {0};
    int leftest[56]    = {0}; // rightest position of that character seen
    int rightest[56]   = {0}; // leftest position of that character seen

    int len = strlen(line);
    len = (len % 2) ? len : len - 1; // fgets reads the new line and the last line has no newline
    for(int i = 0; i < len; i++)
    {
        int ch = char_to_index(line[i]);
        times_seen[ch]++;
        if(times_seen[ch] == 1)
            leftest[ch] = i;
        else
            rightest[ch] = i;

        if(times_seen[ch] > 1)
            if(leftest[ch] < len/2 && rightest[ch] >= len/2) {
                sum += ch + 1;
                break;
            }
    }
}

int gn = 0;
int times_seen[56][3] = {0};

void part2(char *line)
{
    for(int i = 0; line[i] != '\n' && line[i] != '\0'; i++)
        times_seen[char_to_index(line[i])][gn]++;
    gn++;

    if(gn == 3) {
        for(int j = 0; j < 56; j++)
            if(times_seen[j][0] && times_seen[j][1] && times_seen[j][2]) {
                sum += j + 1;
                break;
            }
        gn = 0;
        memset(times_seen, 0, sizeof(times_seen));
    }

}

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) != NULL)
        PART(line);

    fclose(fp);
}

int main(void)
{
    parse();
    printf("%d\n", sum);
    return 0;
}