Advent of Code: Day #12 - Rain Risk

12th of December 2020 |

4 - 5 minutes

Introduction

A storm has hit the ferry! Thankfully we are here to fix the computer and get us back on track.

Task One

Instructions are given in the form LetterNum where letter is N, E, S, W, F, B, L or R. If the letter is L(eft) or R(ight) then the number will be a multiple of 90. If the instruction is N,E,S or W then we move the boat num amount in that direction. Forward or Back move the boat by num in the current direction. The boat starts facing east.

Reading in the data

I read the data into an array of tuples where the first element is the instruction and the second is an integer

Python Copy
def read_data(path):
dataset = []
with open(path) as f:
for line in f.readlines():
tmp = line.rstrip()
dataset.append((tmp[0], int(tmp[1:])))

return dataset

The Solution

Every iteration of the loop we get the current instruction and the associated number. If it's forward then we increment the respective element in the momentum dictionary by num. If it is Right or Left we increment the heading and set the new current_direction, if it's left then we subtract the angle from 360 so we can use the code for turning right for also turning left. If its a direction then we increase the momentum dictionary the specified amount.

Python Copy
def task_one(dirs):
momentum = {"N": 0, "E": 0, "S": 0, "W": 0}

compass = ["N", "E", "S", "W"]
heading = 1
current_direction = compass[heading]

for instruction, num in dirs:
if instruction == "F":
momentum[current_direction] += num
elif instruction in ["R", "L"]:
if instruction == "L":
num = 360 - num
heading += (num // 90)
heading %= 4
current_direction = compass[heading]
else:
momentum[instruction] += num

return abs(momentum["N"] - momentum["S"]) + abs(momentum["E"] - momentum["W"])

Task Two

The Solution

For task two we learn that the instructions are for actually moving a waypoint instead of the boat. I tried the just make a few tweaks to part one to get it working but in the end realised it would be faster to just re-write the code.

Python Copy
def task_two(dirs):
wx, wy = 10, 1
x = y = 0
compass = {"N": 1, "E": 1, "S": -1, "W": -1}

for instruction, num in dirs:

if instruction in ["N", "S"]:
wy += num * compass[instruction]
if instruction in ["E", "W"]:
wx += num * compass[instruction]

elif instruction == "F":
x += wx * num
y += wy * num

elif instruction in ["R", "L"]:
# Swap around for every turn of the compass
for _ in range(num // 90):
if instruction == "R":
wx, wy = wy, -wx
else:
wx, wy = -wy, wx

return abs(y) + abs(x)

Leaderboard Code: 353270-1fc6ef28

Github Repository A link to the github repo containing all the days.

main.py A direct download of the main.py script

1.8Kb