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

#if 0
  #define PART part1
#else
  #define PART part2
#endif

#if 0
  #define FILENAME "sample.txt"
  #define WIDTH  600
  #define HEIGHT 20
#else
  #define FILENAME "input.txt"
  #define WIDTH  2000
  #define HEIGHT 500
#endif

#define MAX(x, y) (((x) > (y)) ? (x) : (y))
#define MIN(x, y) (((x) < (y)) ? (x) : (y))

int map[WIDTH][HEIGHT] = {0};
int max_y = INT_MIN;
int sands = 0;

int sim_sand()
{
    int sand_x = 500;
    int sand_y = 0;
    while(1) {
        if(sand_y >= max_y)
            return -1;

        if(map[sand_x][sand_y + 1] != 1) {
            sand_y++;
        } else if(map[sand_x - 1][sand_y + 1] != 1) {
            sand_x--; sand_y++;
        } else if(map[sand_x + 1][sand_y + 1] != 1) {
            sand_x++; sand_y++;
        } else break;

        continue;
    }

    map[sand_x][sand_y] = 1;
    return 0;
}

void part1()
{
    while(sim_sand() == 0)
        sands++;
}

void draw_line(int x1, int y1, int x2, int y2);

void part2()
{
    draw_line(0, max_y + 2, WIDTH-1, max_y + 2);
    max_y = INT_MAX;

    while(map[500][0] != 1) {
        sim_sand();
        sands++;
    }
}

void draw_line(int x1, int y1, int x2, int y2)
{
    if(x1 != x2 && y1 == y2)
        for(int x = MIN(x1, x2); x <= MAX(x1, x2); x++)
            map[x][y1] = 1;
    else if(y1 != y2 && x1 == x2)
        for(int y = MIN(y1, y2); y <= MAX(y1, y2); y++)
            map[x1][y] = 1;
}


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

    char line[5000];
    while(fgets(line, sizeof(line), fp))
    {
        int x1 = -1; int y1 = -1;
        int x2 = -1; int y2 = -1;

        char *sprt1;
        char *tok = strtok_r(line, " -> ", &sprt1);
        while(tok != NULL) {

            char *sprt2;
            x2 = atoi(strtok_r(tok, ",", &sprt2));
            y2 = atoi(strtok_r(NULL, ",", &sprt2));
            max_y = MAX(max_y, y2);

            if(x1 != -1 && y1 != -1)
                draw_line(x1, y1, x2, y2);
            x1 = x2; y1 = y2;

            tok = strtok_r(NULL, " -> ", &sprt1);
        }
    }

    fclose(fp);
}

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