summaryrefslogtreecommitdiff
path: root/Advent-of-Code-2020/AOC-5/main.c
blob: 2634753ec43216b367b5310da2ba92b441beecdc (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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

#if 0
#define PART_1
#else
#define PART_2
#endif

#if 0
#define FILE_PATH "example.txt"
#define IDS 4
#else
#define FILE_PATH "input.txt"
#define IDS 908
#endif

#define LOWER(min, max) ((max) - (((max) - (min))/2 + 1))
#define UPPER(min, max) (((min) + (max))/2 + 1)

#define ROWS  128
#define COLUMNS 8

int highest_id = 0;
int ids[IDS] = {0};

void process_pass(char *pass, int index)
{
    int min_r = 0; int max_r = ROWS - 1;
    int min_c = 0; int max_c = COLUMNS - 1;

    for(int i = 0; i < 10; i++)
    {
        switch(pass[i])
        {
        case 'F':
            max_r = LOWER(min_r, max_r);
            break;
        case 'B':
            min_r = UPPER(min_r, max_r);
            break;
        case 'L':
            max_c = LOWER(min_c, max_c);
            break;
        case 'R':
            min_c = UPPER(min_c, max_c);
            break;
        }
    }

    int id = min_r * 8 + min_c;

#ifdef PART_1
    (void)index;
    if(id > highest_id) highest_id = id;
#endif

#ifdef PART_2
    assert(index < IDS);
    ids[index] = id;
#endif

}

void parse()
{
    FILE *fp = fopen(FILE_PATH, "r");
    if(!fp) {
        fprintf(stderr, "ERROR: Could not open file: %s\n", FILE_PATH);
        exit(EXIT_FAILURE);
    }

    int i = 0;
    char line[256] = {0};
    while(fgets(line, sizeof(line), fp) != NULL)
    {
        if(line[10] == '\n') line[10] = '\0';
        process_pass(line, i);
        i++;
    }

    fclose(fp);
}

int find_id()
{
    int your_seat;
    int seat_missing;

    for(int i = 0; i < IDS; i++)
    {
        your_seat    = -1;
        seat_missing = 0;

        for(int j = 0; j < IDS; j++)
        {
            if(ids[i] == (ids[j] + 2))
            {
                your_seat = ids[i] - 1;
                seat_missing = 1;

                for(int k = 0; k < IDS; k++)
                    if(your_seat == ids[k]) seat_missing = 0;
            }
        }

        if(your_seat!= -1 && seat_missing != 0)
            return your_seat;

    }
    return -1;
}

void part_1()
{
    printf("Highest boarding ID is %d\n", highest_id);
}

void part_2()
{
    printf("Your id is: %d\n", find_id());
}

int main(void)
{
    parse();

#ifdef PART_1
    part_1();
#endif
#ifdef PART_2
    part_2();
#endif

    return 0;
}