Solve 2018 day 21, 2020 day 12 and improve 2022 day 19

This commit is contained in:
2024-09-13 20:22:22 -04:00
parent 9cd17279d9
commit 4a72eeb348
4 changed files with 192 additions and 111 deletions

82
2020/d12.py Normal file
View File

@@ -0,0 +1,82 @@
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()