diff options
author | Cody Hiar <cody@hiar.ca> | 2021-03-19 13:46:12 -0600 |
---|---|---|
committer | Cody Hiar <cody@hiar.ca> | 2021-03-19 13:46:12 -0600 |
commit | 0b5a75dbda2c332b01e6869c3ccf7f3f57140ee7 (patch) | |
tree | 33d5326104768bcd0e54684de830316096e196e5 /day12/day12.py | |
parent | 137d68f807702b83d4d05a1653997afe4cd9749a (diff) |
day 12
Diffstat (limited to 'day12/day12.py')
-rw-r--r-- | day12/day12.py | 102 |
1 files changed, 102 insertions, 0 deletions
diff --git a/day12/day12.py b/day12/day12.py new file mode 100644 index 0000000..2476725 --- /dev/null +++ b/day12/day12.py @@ -0,0 +1,102 @@ +"""Day 12.""" +import math + +with open("input") as f: + instructions = f.read().rstrip().split("\n") + +DIRECTIONS = ("N", "E", "S", "W") +CURRENT_DIRECTION = "E" +CORDS = { + "x": 0, + "y": 0, +} +WAYPOINT = { + 'x': 10, + 'y': 1, +} + + +def left(current_direction, degree): + idx = DIRECTIONS.index(current_direction) - (degree // 90) + return DIRECTIONS[idx % len(DIRECTIONS)] + + +def right(current_direction, degree): + idx = DIRECTIONS.index(current_direction) + (degree // 90) + return DIRECTIONS[idx % len(DIRECTIONS)] + + +def update_coords(direction, value): + if direction == "N": + CORDS["y"] += value + if direction == "E": + CORDS["x"] += value + if direction == "S": + CORDS["y"] -= value + if direction == "W": + CORDS["x"] -= value + + +for inst in instructions: + direction, value = inst[0], int(inst[1:]) + if direction == "L": + CURRENT_DIRECTION = left(CURRENT_DIRECTION, value) + elif direction == "R": + CURRENT_DIRECTION = right(CURRENT_DIRECTION, value) + elif direction == "F": + update_coords(CURRENT_DIRECTION, value) + else: + update_coords(direction, value) + +# Part 1 +part_1 = abs(CORDS["x"]) + abs(CORDS["y"]) +print(part_1) +assert part_1 == 882 + +# reset coords +CORDS = { + "x": 0, + "y": 0, +} + +def update_waypoint(direction, value): + if direction == "N": + WAYPOINT["y"] += value + if direction == "E": + WAYPOINT["x"] += value + if direction == "S": + WAYPOINT["y"] -= value + if direction == "W": + WAYPOINT["x"] -= value + + +def clockwise(degrees): + """rotate clockwise.""" + x = WAYPOINT["x"] + y = WAYPOINT["y"] + rads = math.radians(degrees % 360) + return ( + round(x * math.cos(rads) + y * math.sin(rads)), + round(-x * math.sin(rads) + y * math.cos(rads)) + ) + +for inst in instructions: + direction, value = inst[0], int(inst[1:]) + if direction == "L": + newx, newy = clockwise(360 - value) + WAYPOINT["x"] = newx + WAYPOINT["y"] = newy + elif direction == "R": + newx, newy = clockwise(value) + WAYPOINT["x"] = newx + WAYPOINT["y"] = newy + elif direction == "F": + CORDS["x"] += WAYPOINT["x"] * value + CORDS["y"] += WAYPOINT["y"] * value + else: + update_waypoint(direction, value) + + +part_2 = abs(CORDS["x"]) + abs(CORDS["y"]) +assert part_2 == 28885 +print(part_2) |