From e7c9108b95e39d7ea5a29ae06d619c4727f11027 Mon Sep 17 00:00:00 2001 From: Thomas Voss Date: Fri, 29 Oct 2021 23:02:39 +0200 Subject: Initial commit --- 2020/12/puzzle-2.c | 79 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 2020/12/puzzle-2.c (limited to '2020/12/puzzle-2.c') diff --git a/2020/12/puzzle-2.c b/2020/12/puzzle-2.c new file mode 100644 index 0000000..8ac34b4 --- /dev/null +++ b/2020/12/puzzle-2.c @@ -0,0 +1,79 @@ +#include +#include +#include +#include + +struct coords { + int north; + int east; +}; + +int +main(void) +{ + FILE *fp; + char cl[6]; + struct coords waypoint = {1, 10}; + struct coords ship = {0, 0}; + + if (!(fp = fopen("input", "r"))) + err(EXIT_FAILURE, "fopen"); + + while (fgets(cl, sizeof(cl), fp) != NULL) { + switch (cl[0]) { + case 'N': + waypoint.north += atoi(&cl[1]); + break; + case 'E': + waypoint.east += atoi(&cl[1]); + break; + case 'S': + waypoint.north -= atoi(&cl[1]); + break; + case 'W': + waypoint.east -= atoi(&cl[1]); + break; + case 'F':; + unsigned int const val = atoi(&cl[1]); + ship.north += val * waypoint.north; + ship.east += val * waypoint.east; + break; + /* Left and right */ + default:; + int direction = atoi(&cl[1]); + + /* (x, y) -> (-x, -y) */ + if (direction == 180) { + waypoint.north = -waypoint.north; + waypoint.east = -waypoint.east; + break; + } + + /* 0 <= direction < 360 */ + if (cl[0] == 'R') + direction = -direction + 360; + + int const temp = waypoint.east; + if (direction == 90) { + /* (x, y) -> (-y, x) */ + waypoint.east = -waypoint.north; + waypoint.north = temp; + } else { + /* (x, y) -> (y, -x) */ + waypoint.east = waypoint.north; + waypoint.north = -temp; + } + break; + } + } + fclose(fp); + + /* Absolute value */ + if (ship.north < 0) + ship.north = -ship.north; + if (ship.east < 0) + ship.east = -ship.east; + + printf("%d\n", ship.north + ship.east); + return EXIT_SUCCESS; +} -- cgit v1.2.3