summaryrefslogtreecommitdiff
path: root/Advent-of-Code-2022/aoc-9/main.c
blob: 00945eb5963cd412b3ac0daa218721f44647e0ef (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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#if 0
  #define KNOTS 2
#else
  #define KNOTS 10
#endif

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

#define SIDE 1000
#define OFFSET (SIDE/2)

typedef enum {
    NONE = 0,
    NORTH = 1,
    SOUTH = -1,
    EAST = 1,
    WEST = -1
} direction;

int board[SIDE][SIDE] = {0};
int rope[KNOTS][2] = {0};
direction rope_dir[KNOTS][2] = {0};

void move(int k)
{
    rope[k][0] += rope_dir[k][0];
    rope[k][1] += rope_dir[k][1];
}

void parse_dir(char d)
{
    rope_dir[0][0] = NONE;
    rope_dir[0][1] = NONE;

    switch(d) {
    case 'U':
        rope_dir[0][1] = NORTH;
        return;
    case 'D':
        rope_dir[0][1] = SOUTH;
        return;
    case 'R':
        rope_dir[0][0] = EAST;
        return;
    case 'L':
        rope_dir[0][0] = WEST;
        return;
    }
}

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))
    {
        parse_dir(strtok(line, " ")[0]);
        int n = atoi(strtok(NULL, " "));

        for(int i = 0; i < n; i++)
        {
            move(0);
            for(int j = 1; j < KNOTS; j++)
            {
                int hor  = rope[j-1][0] - rope[j][0];
                if(hor > 0) rope_dir[j][0] = EAST;
                else if(hor < 0) rope_dir[j][0] = WEST;
                else rope_dir[j][0] = NONE;

                int vert = rope[j-1][1] - rope[j][1];
                if(vert > 0) rope_dir[j][1] = NORTH;
                else if(vert < 0) rope_dir[j][1] = SOUTH;
                else rope_dir[j][1] = NONE;

                if(abs(vert) > 1 || abs(hor) > 1)
                    move(j);
            }

            board[rope[KNOTS-1][0] + OFFSET][rope[KNOTS-1][1] + OFFSET]++;
        }
    }

    fclose(fp);
}

int sum()
{
    int sum = 0;
    for(int i = 0; i < SIDE; i++)
        for(int j = 0; j < SIDE; j++)
            if(board[j][i] > 0) sum++;
    return sum;
}

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