Advent of Code: Day #12 - Rain Risk
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
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.
def task_one(dirs):momentum = {"N": 0, "E": 0, "S": 0, "W": 0}compass = ["N", "E", "S", "W"]heading = 1current_direction = compass[heading]for instruction, num in dirs:if instruction == "F":momentum[current_direction] += numelif instruction in ["R", "L"]:if instruction == "L":num = 360 - numheading += (num // 90)heading %= 4current_direction = compass[heading]else:momentum[instruction] += numreturn 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.
def task_two(dirs):wx, wy = 10, 1x = y = 0compass = {"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 * numy += wy * numelif instruction in ["R", "L"]:# Swap around for every turn of the compassfor _ in range(num // 90):if instruction == "R":wx, wy = wy, -wxelse:wx, wy = -wy, wxreturn abs(y) + abs(x)
Links
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