diff options
Diffstat (limited to 'Advent-of-Code-2020/AOC-3/main.c')
-rw-r--r-- | Advent-of-Code-2020/AOC-3/main.c | 122 |
1 files changed, 122 insertions, 0 deletions
diff --git a/Advent-of-Code-2020/AOC-3/main.c b/Advent-of-Code-2020/AOC-3/main.c new file mode 100644 index 0000000..6690b5d --- /dev/null +++ b/Advent-of-Code-2020/AOC-3/main.c @@ -0,0 +1,122 @@ +#include <stdio.h> +#include <stdlib.h> +#include <assert.h> + +#if 0 +#define PART_1 +#else +#define PART_2 +#endif + +#if 0 +#define FILE_PATH "example.txt" +#else +#define FILE_PATH "input.txt" +#endif + +int WIDTH = 0; +int HEIGHT = 0; +#define BOARD_SZ ((WIDTH) * (HEIGHT)) + +char *board; + +void parse() +{ + FILE *fp = fopen(FILE_PATH, "r"); + if(!fp) { + fprintf(stderr, "ERROR: Could not open file: %s", FILE_PATH); + } + + char ch; + int i = 0; + // calculate size of the board + while((ch = fgetc(fp)) != EOF) + { + if(ch != '\n') { + i++; + continue; + } + + if(WIDTH == 0) WIDTH = i; + } + HEIGHT = i / WIDTH; + board = malloc(BOARD_SZ); + + fseek(fp, 0, SEEK_SET); + i = 0; + while((ch = fgetc(fp)) != EOF) + { + if(ch == '\n') continue; + + board[i] = ch; + i++; + } + + fclose(fp); +} + +size_t traverse_map() +{ +#ifdef PART_1 + int slope_x[1] = {3}; + int slope_y[1] = {1}; + #define SZ 1 +#endif +#ifdef PART_2 + int slope_x[5] = {1, 3, 5, 7, 1}; + int slope_y[5] = {1, 1, 1, 1, 2}; + #define SZ 5 + size_t result = 1; +#endif + + int x, y; + size_t hit_trees; + for(int i = 0; i < SZ; i++) + { + x = 0; + y = 0; + hit_trees = 0; + while(y != (HEIGHT - 1)) + { + x += slope_x[i]; + y += slope_y[i]; + + if(x >= WIDTH) + x = x - WIDTH; + + if(board[y * WIDTH + x] == '#') + hit_trees++; + } + + #ifdef PART_2 + result *= hit_trees; + #endif + } + + #ifdef PART_1 + return hit_trees; + #endif + #ifdef PART_2 + return result; + + #endif +} + +void print_board() +{ + for(int i = 0; i < BOARD_SZ; i++) + { + printf("%c", board[i]); + + if(i % WIDTH == (WIDTH - 1)) + putc('\n', stdout); + } +} + +int main(void) +{ + parse(); + printf("You hit %ld trees", traverse_map()); + free(board); + return 0; +} |