summaryrefslogtreecommitdiff
path: root/5/part2_fast.c
blob: 23343904f8e26d56ddcdd9d9af8a2706dd16968e (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
#include <stdio.h>

#define COLUMNS 8
#define ROWS 128

int row(const char *seat)
{
    int end_res = 0;
    for (int i = 0; i < 7; i++) {
        if (seat[i] == 'B') {
            end_res |= 0x40 >> i;
        }
    }

    return end_res;
}

int column(const char *seat)
{
    int end_res = 0;
    for (int i = 7; i < 10; i++) {
        if (seat[i] == 'R') {
            end_res |= 0x200 >> i;
        }
    }

    return end_res;
}

int seat_id(const char *seat)
{
    int end_res = 0;
    int i = 0;
    for (; i < 7; i++) {
        if (seat[i] == 'B') {
            end_res |= 0x200 >> i;
        }
    }

    for (; i < 10; i++) {
        if (seat[i] == 'R') {
            end_res |= 0x200 >> i;
        }
    }

    return end_res;
}

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 < min) {
            min = tmp;
        }
        else if (tmp > max) {
            max = tmp;
        }

        table[tmp] = 1;
    }

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

    fclose(file);

    return 0;
}

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