summaryrefslogtreecommitdiff
path: root/Advent-of-Code-2021/AOC-20/main.c
diff options
context:
space:
mode:
Diffstat (limited to 'Advent-of-Code-2021/AOC-20/main.c')
-rw-r--r--Advent-of-Code-2021/AOC-20/main.c144
1 files changed, 144 insertions, 0 deletions
diff --git a/Advent-of-Code-2021/AOC-20/main.c b/Advent-of-Code-2021/AOC-20/main.c
new file mode 100644
index 0000000..1dbcdc9
--- /dev/null
+++ b/Advent-of-Code-2021/AOC-20/main.c
@@ -0,0 +1,144 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <assert.h>
+#include <string.h>
+
+#if 0
+#define PART_1
+#else
+#define PART_2
+#endif
+
+#if 0
+ #define FILE_PATH "example.txt"
+ #define T_WIDTH 5
+ #define T_HEIGHT 5
+#else
+ #define FILE_PATH "input.txt"
+ #define T_WIDTH 100
+ #define T_HEIGHT 100
+#endif
+
+#define WIDTH 256
+#define HEIGHT 256
+
+#define OFFSET_X ((WIDTH/2) - (T_WIDTH/2))
+#define OFFSET_Y ((HEIGHT/2) - (T_HEIGHT/2))
+
+
+int board[WIDTH][HEIGHT];
+int new_board[WIDTH][HEIGHT];
+int enchance_alg[512];
+
+void parse()
+{
+ FILE *fp = fopen(FILE_PATH, "r");
+ if(!fp) {
+ fprintf(stderr, "ERROR: Could not open file: %s\n", FILE_PATH);
+ exit(EXIT_FAILURE);
+ }
+
+ char line[1024] = {0};
+
+ fgets(line, sizeof(line), fp);
+ for(int i = 0; i < 512; i++)
+ if(line[i] == '.')
+ enchance_alg[i] = 0;
+ else
+ enchance_alg[i] = 1;
+
+ fgets(line, sizeof(line), fp);
+
+ char ch;
+ int i = 0;
+ while((ch = getc(fp)) != EOF)
+ {
+ if(ch == '\n') continue;
+ else if(ch == '.')
+ board[i%T_WIDTH + OFFSET_X][i/T_WIDTH + OFFSET_Y] = 0;
+ else if(ch == '#')
+ board[i%T_WIDTH + OFFSET_X][i/T_WIDTH + OFFSET_Y] = 1;
+
+ i++;
+ }
+
+
+ fclose(fp);
+}
+
+int generate_index(int *vals)
+{
+ int index = 0;
+ for(int i = 0; i < 9; i++)
+ {
+ index |= (vals[8-i] & 1)<< i;
+ }
+ return index;
+}
+
+void enchance()
+{
+ for(int i = 0; i < HEIGHT; i++)
+ {
+ for(int j = 0; j < WIDTH; j++)
+ {
+ int vals[9];
+ for(int y = -1; y <= 1; y++)
+ for(int x = -1; x <= 1; x++)
+ {
+ int vals_i = (y+1) * 3 + (x+1);
+ if(i+y < 0 || i+y >= HEIGHT ||
+ j+x < 0 || j+x >= WIDTH)
+ vals[vals_i] = board[j][i];
+ else
+ vals[vals_i] = board[j+x][i+y];
+ }
+ new_board[j][i] = enchance_alg[generate_index(vals)];
+ }
+ }
+ memcpy(board, new_board, sizeof(board));
+}
+
+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 putc('#', stdout);
+
+ putc('\n', stdout);
+ }
+}
+
+void print_alg()
+{
+ for(int i = 0; i < 512; i++)
+ {
+ if(enchance_alg[i] == 0) putc('.', stdout);
+ else putc('#', stdout);
+ }
+ putc('\n', stdout);
+}
+
+
+int main(void)
+{
+ parse();
+
+#ifdef PART_1
+ for(int i = 0; i < 2; i++)
+#endif
+#ifdef PART_2
+ for(int i = 0; i < 50; i++)
+#endif
+ enchance();
+
+ int lit = 0;
+ for(int i = 0; i < HEIGHT; i++)
+ for(int j = 0; j < WIDTH; j++)
+ if(board[j][i] == 1) lit++;
+
+ printf("%d pixels are lit\n", lit);
+ return 0;
+}