summaryrefslogtreecommitdiff
path: root/2020/12/part1.c
blob: 7ee0f4a9cf6096196424ab99ba781a7115b8490a (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
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>

#define MAX_INPUT_WIDTH 128
#define MAX_INPUT_HEIGTH 128
#define MAX_INPUT MAX_INPUT_WIDTH * MAX_INPUT_HEIGTH

enum direction {
    North,
    East,
    South,
    West
};

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

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

    enum direction dir = East;
    int hor = 0;
    int ver = 0;
    while (fgets(buffer, 8, file)) {
        int n = atoi(buffer + 1);
        switch (buffer[0]) {
            case 'N':
                ver += n;
                break;
            case 'E':
                hor += n;
                break;
            case 'S':
                ver -= n;
                break;
            case 'W':
                hor -= n;
                break;
            case 'F':
                switch (dir) {
                    case North:
                        ver += n;
                        break;
                    case East:
                        hor += n;
                        break;
                    case South:
                        ver -= n;
                        break;
                    case West:
                        hor -= n;
                        break;
                }
                break;
            case 'R':
                dir = (enum direction)(((int)dir + (n / 90)) % 4);
                break;
            case 'L':
                dir = (enum direction)((abs(4 + ((int)dir - (n / 90))) % 4));
                break;
            default:
                break;
        }
    }

    fclose(file);

    return abs(ver) + abs(hor);
}

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