summaryrefslogtreecommitdiff
path: root/Advent-of-Code-2021/AOC-5/main.c
diff options
context:
space:
mode:
Diffstat (limited to 'Advent-of-Code-2021/AOC-5/main.c')
-rw-r--r--Advent-of-Code-2021/AOC-5/main.c138
1 files changed, 138 insertions, 0 deletions
diff --git a/Advent-of-Code-2021/AOC-5/main.c b/Advent-of-Code-2021/AOC-5/main.c
new file mode 100644
index 0000000..ea39e06
--- /dev/null
+++ b/Advent-of-Code-2021/AOC-5/main.c
@@ -0,0 +1,138 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <assert.h>
+#include <string.h>
+
+#define MAX(x, y) (((x) > (y)) ? (x) : (y))
+#define MIN(x, y) (((x) < (y)) ? (x) : (y))
+
+#if 0
+#define PART_1
+#else
+#define PART_2
+#endif
+
+#if 0
+#define FILE_PATH "example.txt"
+#define WIDTH 10
+#define HEIGHT 10
+#else
+#define FILE_PATH "input.txt"
+#define WIDTH 10000
+#define HEIGHT 10000
+#endif
+
+int board[WIDTH][HEIGHT] = {0};
+
+void draw_line(int x1, int y1, int x2, int y2)
+{
+ if(x1 == x2)
+ {
+ for(int y = MIN(y1, y2); y <= MAX(y1, y2); y++)
+ board[x1][y]++;
+
+ }
+ else if(y1 == y2)
+ {
+ for(int x = MIN(x1, x2); x <= MAX(x1, x2); x++)
+ board[x][y1]++;
+ }
+#ifdef PART_2
+ else
+ {
+ int direction_x = (x1 < x2) ? 1 : -1;
+ int direction_y = (y1 < y2) ? 1 : -1;
+
+ int y = y1;
+ int x = x1;
+ while(!((y == y2) && (x == x2)))
+ {
+ board[x][y]++;
+ x+=direction_x;
+ y+=direction_y;
+ }
+ }
+#endif
+}
+
+void parse()
+{
+ FILE *fp = fopen(FILE_PATH, "r");
+ if(!fp) {
+ fprintf(stderr, "ERROR: Could not open file: %s", FILE_PATH);
+ exit(EXIT_FAILURE);
+ }
+
+ char *vec1, *vec2;
+ char line[256];
+ while(fgets(line, sizeof(line), fp) != NULL)
+ {
+ vec1 = strtok(line, " -> ");
+ vec2 = strtok(NULL, " -> ");
+
+ int x1, y1, x2, y2;
+ x1 = atoi(strtok(vec1, ","));
+ y1 = atoi(strtok(NULL, ","));
+ x2 = atoi(strtok(vec2, ","));
+ y2 = atoi(strtok(NULL, ","));
+
+ draw_line(x1, y1, x2, y2);
+ }
+}
+
+void print_board()
+{
+ for(int i = 0; i < HEIGHT; i++)
+ {
+ for(int j = 0; j < WIDTH; j++)
+ {
+ if(board[j][i] == 0)
+ putc('.', stdout);
+ else if(board[j][i] == 1)
+ putc('#', stdout);
+ else
+ putc('@', stdout);
+ }
+ putc('\n', stdout);
+ }
+}
+
+void part_1()
+{
+ parse();
+
+ int count = 0;
+ for(int i = 0; i < HEIGHT; i++)
+ for(int j = 0; j < WIDTH; j++)
+ if(board[j][i] >= 2) count++;
+
+ printf("Count is %d\n", count);
+}
+
+void part_2()
+{
+ parse();
+
+ int count = 0;
+ for(int i = 0; i < HEIGHT; i++)
+ for(int j = 0; j < WIDTH; j++)
+ if(board[j][i] >= 2) count++;
+
+ // print_board();
+
+ printf("Count is %d\n", count);
+}
+
+int main(void)
+{
+
+#ifdef PART_1
+ part_1();
+#endif
+
+#ifdef PART_2
+ part_2();
+#endif
+
+ return 0;
+}