summaryrefslogtreecommitdiff
path: root/5/part2.c
blob: 21dbdc227ba871fee9a8f4e82339961acfb05aaa (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
#include <stdio.h>

#define COLUMNS 8
#define ROWS 128

int seat_id(const char *seat)
{
    int row = 0;
    int row_lower = 0;
    int row_upper = ROWS - 1;
    int column = 0;
    int column_lower = 0;
    int column_upper = COLUMNS - 1;
    int i = 0;
    for (; i < 6; i++) {
        switch (seat[i]) {
            case 'F':
                row_upper -= (row_upper - row_lower + 1) / 2;
                break;
            case 'B':
                row_lower += (row_upper - row_lower + 1) / 2;
                break;
        }
    }

    switch (seat[i++]) {
        case 'F':
            row = row_lower;
            break;
        case 'B':
            row = row_upper;
            break;
    }

    for (; i < 9; i++) {
        switch (seat[i]) {
            case 'L':
                column_upper -= (column_upper - column_lower + 1) / 2;
                break;
            case 'R':
                column_lower += (column_upper - column_lower + 1) / 2;
                break;
        }
    }

    switch (seat[i++]) {
        case 'L':
            column = column_lower;
            break;
        case 'R':
            column = column_upper;
            break;
    }

    return row * COLUMNS + column;
}

int missing_seat_id(const char *filename)
{
    FILE *file = fopen(filename, "r");

    char table[COLUMNS * ROWS] = { 0 };

    // Include space for newline and string terminator
    char buffer[16] = { 0 };

    int min = __INT_MAX__;
    int max = 0;
    while (fgets(buffer, 16, file)) {
        int tmp = seat_id(buffer);
        if (tmp > max)
        {
            max = tmp;
        }

        if (tmp < min)
        {
            min = tmp;
        }

        table[tmp] = 1;
    }

    for (int i = min + 1; i < max; i++) {
        if (table[i] == 0) {
            return i;
        }
    }

    return 0;
}

int main(int argc, char *argv[])
{
    printf("%i", missing_seat_id(argv[argc - 1]));
}