## DEV Community is a community of 604,099 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

loading...

# Advent of Code 2020: Python Solution Day 12

This is not that much hard challenge than previous day's but still it took my plenty of time. I wrote solution for part one by myself and I had to take help for part 2 from here, so credit goes to the author. I have updated my Notebook also.

## Part 1

``````with open("day12.txt", "r") as fp:
lines = [(line.rstrip(), int(line.rstrip()[1:]))  for line in fp.readlines()]
dirs = ["E", "S", "W", "N", "L", "R", "F"]
curr_dir = "E"

curr_state = {"E":0, "W":0, "N":0, "S":0}

for line in lines:
if line == "F":
curr_state[curr_dir] += line

if line == "R":
av = ["E", "S", "W", "N"]
angle = line
v = int(angle/90)
ndir = (av.index(curr_dir)+v) % len(av)
ndir = av[ndir]
curr_dir = ndir

if line == "L":
av = ["E", "N", "W", "S"]
angle = line
v = int(angle/90)
ndir = (av.index(curr_dir)+v) % len(av)
ndir = av[ndir]
curr_dir = ndir

if line == "N":
curr_state["N"] += line
if line == "S":
curr_state["S"] += line
if line == "W":
curr_state["W"] += line
if line == "E":
curr_state["E"] += line

d = curr_state["E"]-curr_state["W"], curr_state["S"]-curr_state["N"]
print(f"Manhattan Distance of current positions from starting i.e. {curr_state} = {d+d}")
``````

## Part 2

``````# ref https://github.com/vesche/adventofcode-2020/blob/master/day12.py
import math

def rotate(origin, point, angle):
# source: https://stackoverflow.com/a/34374437
ox, oy = origin
px, py = point
qx = ox + math.cos(angle) * (px - ox) - math.sin(angle) * (py - oy)
qy = oy + math.sin(angle) * (px - ox) + math.cos(angle) * (py - oy)
return int(round(qx)), int(round(qy))

coord = {'x': 0, 'y': 0}
waypoint = {'x': 10, 'y': 1}
for line in lines:
instruction, n = line
if instruction == 'N':
waypoint['y'] += n
elif instruction == 'S':
waypoint['y'] -= n
elif instruction == 'E':
waypoint['x'] += n
elif instruction == 'W':
waypoint['x'] -= n
elif instruction == 'F':
coord['y'] += waypoint['y'] * n
coord['x'] += waypoint['x'] * n
elif instruction in ['L', 'R']:
if instruction == 'R':
n = -n
waypoint['x'], waypoint['y'] = rotate(
(0, 0), (waypoint['x'], waypoint['y']), math.radians(n)
)
abs(coord['x']) + abs(coord['y'])

``````

Lets share yours too.

## Discussion (0) 