Created
December 12, 2020 12:52
-
-
Save kung-foo/521793102aa595c9d50a995d59ae2d43 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import numpy as np | |
src = open("input.txt", "r").readlines() | |
src = [r.strip() for r in src] | |
src = [[line[0], int(line[1:])] for line in src] | |
d2s = { | |
0: "N", | |
90: "E", | |
180: "S", | |
270: "W", | |
} | |
vec = { | |
"N": np.array([0, 1]), | |
"E": np.array([1, 0]), | |
"S": np.array([0, -1]), | |
"W": np.array([-1, 0]), | |
} | |
def make_rotation(r): | |
theta = np.radians(r) | |
return np.array(((np.cos(theta), -np.sin(theta)), (np.sin(theta), np.cos(theta)))) | |
rot = { | |
-90: make_rotation(-90), | |
-180: make_rotation(-180), | |
-270: make_rotation(-270), | |
90: make_rotation(90), | |
180: make_rotation(180), | |
270: make_rotation(270), | |
} | |
def rotate(vec, r): | |
return np.rint(vec.dot(rot[r])).astype(int) | |
def part1(): | |
pos = np.array([0, 0]) | |
d = 90 | |
for r in src: | |
a, v = r | |
if a == "R": | |
d = (d + v) % 360 | |
elif a == "L": | |
d = (d - v) % 360 | |
elif a in ("N", "E", "S", "W"): | |
pos += vec[a] * v | |
elif a == "F": | |
pos += vec[d2s[d]] * v | |
print(pos, abs(pos[0]) + abs(pos[1])) | |
def part2(): | |
pos = np.array([0, 0]) | |
wpos = np.array([10, 1]) | |
for r in src: | |
a, v = r | |
if a in ("N", "E", "S", "W"): | |
wpos += vec[a] * v | |
elif a == "R": | |
wpos = rotate(wpos, v) | |
elif a == "L": | |
wpos = rotate(wpos, -v) | |
elif a == "F": | |
pos += wpos * v | |
print(pos, abs(pos[0]) + abs(pos[1])) | |
part1() | |
part2() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment