You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
55 lines
1.5 KiB
55 lines
1.5 KiB
import os
|
|
import sys
|
|
|
|
inputfile = os.path.join(os.path.dirname(__file__), "input/day03_input")
|
|
|
|
|
|
def draw_path(inst):
|
|
path = set()
|
|
dists = {}
|
|
cnt = 0
|
|
ptr = (0, 0)
|
|
for d, l in ((x[0], x[1:]) for x in inst.split(',')):
|
|
for _ in range(int(l)):
|
|
if d == 'D':
|
|
ptr = (ptr[0], ptr[1] - 1)
|
|
elif d == 'R':
|
|
ptr = (ptr[0] + 1, ptr[1])
|
|
elif d == 'U':
|
|
ptr = (ptr[0], ptr[1] + 1)
|
|
else:
|
|
ptr = (ptr[0] - 1, ptr[1])
|
|
cnt += 1
|
|
if ptr not in dists or dists[ptr] > cnt:
|
|
dists[ptr] = cnt
|
|
path.add(ptr)
|
|
return (path, dists)
|
|
|
|
|
|
def test_day3a():
|
|
paths = []
|
|
result = sys.maxsize
|
|
|
|
with open(inputfile) as fp:
|
|
for line in fp.readlines():
|
|
paths.append(draw_path(line)[0])
|
|
for x, y in paths[0].intersection(paths[1]):
|
|
dist = abs(x) + abs(y)
|
|
result = dist if dist < result else result
|
|
assert result == 399
|
|
|
|
|
|
def test_day3b():
|
|
paths = []
|
|
distances = []
|
|
result = sys.maxsize
|
|
|
|
with open(inputfile) as fp:
|
|
for line in fp.readlines():
|
|
computed = draw_path(line)
|
|
paths.append(computed[0])
|
|
distances.append(computed[1])
|
|
for point in paths[0].intersection(paths[1]):
|
|
dist = distances[0][point] + distances[1][point]
|
|
result = dist if dist < result else result
|
|
assert result == 15678
|
|
|