From bb3355014ff5df4376d82baedb4f88d4d1dc7da0 Mon Sep 17 00:00:00 2001 From: Bill Rossi Date: Fri, 6 Dec 2024 07:32:38 -0500 Subject: [PATCH] c 2024 6 part 1 --- c/2024/6/guard_gallivant.c | 119 +++++++++++++++++++++++++++++++++++++ 1 file changed, 119 insertions(+) create mode 100644 c/2024/6/guard_gallivant.c diff --git a/c/2024/6/guard_gallivant.c b/c/2024/6/guard_gallivant.c new file mode 100644 index 0000000..f528496 --- /dev/null +++ b/c/2024/6/guard_gallivant.c @@ -0,0 +1,119 @@ +#include +#include +#include +#include + +#include "../../lib/aoc.h" + +typedef enum Direction { RIGHT, UP, LEFT, DOWN } Direction; + +typedef struct Position { + int x; + int y; +} Position; + +typedef struct Game { + char *map; + int width; + int height; + Position guard; + Direction guard_direction; + int position_count; +} Game; + +Position position_from_index(Game *game, int index) { + Position p = { index % game->width, index / game->width }; + return p; +} + +int index_from_position(Game *game, Position p) { + return p.x + (game->width * p.y); +} + +bool position_inbounds(Game *game, Position p) { + return p.x >= 0 && p.y >= 0 && p.x < game->width && p.y < game->height; +} + +bool guard_inbounds(Game *game) { + return position_inbounds(game, game -> guard); +} + +bool position_has_obstacle(Game *game, Position p) { + return game->map[index_from_position(game, p)] == '#'; +} + +void turn_guard(Game *game) { + Direction new_direction; + switch (game->guard_direction) { + case RIGHT: + new_direction = DOWN; + break; + case UP: + new_direction = RIGHT; + break; + case LEFT: + new_direction = UP; + break; + case DOWN: + new_direction = LEFT; + break; + } + game->guard_direction = new_direction; +} + +void move_guard(Game *game) { + Position target; + target.x = game->guard.x; + target.y = game->guard.y; + switch (game->guard_direction) { + case RIGHT: + target.x++; + break; + case UP: + target.y--; + break; + case LEFT: + target.x--; + break; + case DOWN: + target.y++; + break; + } + + if (position_has_obstacle(game, target)) turn_guard(game); + else { + if (game->map[index_from_position(game, game->guard)] == '.') { + game->map[index_from_position(game, game->guard)] = 'X'; + game->position_count++; + } + + game->guard.x = target.x; + game->guard.y = target.y; + } +} + +int main() { + char *line; + Game game; + game.map = aoc_read_input(); + game.width = strchr(game.map, '\n') - game.map + 1; + game.height = strlen(game.map) / game.width; + game.position_count = 0; + for (int i = 0; i < strlen(game.map); i++) { + if (game.map[i] == '^') { + game.map[i] = '.'; + game.guard = position_from_index(&game, i); + game.guard_direction = UP; + break; + } + } + + while (guard_inbounds(&game)) { + move_guard(&game); + } + + printf("Part 1: %d\n", game.position_count); + + aoc_free(); + return 0; +}