summaryrefslogtreecommitdiff
path: root/Advent-of-Code-2022/aoc-14/main.c
diff options
context:
space:
mode:
authorkartofen <mladenovnasko0@gmail.com>2023-02-10 23:53:15 +0200
committerkartofen <mladenovnasko0@gmail.com>2023-02-10 23:53:15 +0200
commit555091332de32b1d3b36c888ed21898aae540750 (patch)
tree6dd5dc02ecb4d7678d13e5f1265e61e155f33c43 /Advent-of-Code-2022/aoc-14/main.c
parent9f57e15a054b16d335e9d5c49ddd7be829b4e272 (diff)
add a couple of days
Diffstat (limited to 'Advent-of-Code-2022/aoc-14/main.c')
-rw-r--r--Advent-of-Code-2022/aoc-14/main.c122
1 files changed, 122 insertions, 0 deletions
diff --git a/Advent-of-Code-2022/aoc-14/main.c b/Advent-of-Code-2022/aoc-14/main.c
new file mode 100644
index 0000000..7fcfdfa
--- /dev/null
+++ b/Advent-of-Code-2022/aoc-14/main.c
@@ -0,0 +1,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;
+}