Files
aocpy/2020/d12.py

83 lines
2.0 KiB
Python

from lib import get_data
DIRS = {
"N": (-1, 0),
"E": (0, 1),
"S": (1, 0),
"W": (0, -1),
}
def part_1(data):
dir_key = "E"
pos = 0, 0
dirs = "NESW"
for line in data.splitlines():
c = line[0]
v = int(line[1:])
if c in DIRS.keys():
pos = pos[0] + v * DIRS[c][0], pos[1] + v * DIRS[c][1]
elif c == "F":
dir = DIRS[dir_key]
pos = (pos[0] + v * dir[0], pos[1] + v * dir[1])
elif c == "R":
assert v % 90 == 0
dir_key = dirs[(dirs.index(dir_key) + v // 90) % len(dirs)]
elif c == "L":
assert v % 90 == 0
dir_key = dirs[(dirs.index(dir_key) - v // 90) % len(dirs)]
else:
print(c, v)
assert False
print(sum(map(abs, pos)))
def part_2(data):
way_point = (-1, 10)
pos = 0, 0
for line in data.splitlines():
c = line[0]
v = int(line[1:])
if c in DIRS.keys():
way_point = way_point[0] + v * DIRS[c][0], way_point[1] + v * DIRS[c][1]
elif c == "F":
pos = (pos[0] + v * way_point[0], pos[1] + v * way_point[1])
elif c == "R":
row, col = way_point
if v == 90:
way_point = (col, -row)
elif v == 180:
way_point = (-row, -col)
elif v == 270:
way_point = (-col, row)
else:
print(c, v)
assert False
elif c == "L":
row, col = way_point
if v == 90:
way_point = (-col, row)
elif v == 180:
way_point = (-row, -col)
elif v == 270:
way_point = (col, -row)
else:
print(c, v)
assert False
else:
print(c, v)
assert False
print(sum(map(abs, pos)))
def main():
data = get_data(__file__)
part_1(data)
part_2(data)
if __name__ == "__main__":
main()