advent-of-code/2019/day03-path.py

53 lines
1.5 KiB
Python
Raw Normal View History

2020-03-04 22:07:23 +01:00
import collections
import math
def already_seen_on_others(seen, wire, position):
for key, value in seen.items():
if key != wire and position in value:
2020-03-04 22:12:59 +01:00
return value[position]
return None
2020-03-04 22:07:23 +01:00
2020-03-04 22:12:59 +01:00
def distance(seen, position, wire_length):
2020-03-04 22:07:23 +01:00
return int(math.fabs(position[0]) + math.fabs(position[1]))
def main():
with open("inputs/day03") as f:
raw = f.read()
distances = set()
2020-03-04 22:12:59 +01:00
seen_positions = collections.defaultdict(dict)
2020-03-04 22:07:23 +01:00
for wire, line in enumerate(raw.split()):
x, y = 0, 0
2020-03-04 22:12:59 +01:00
wire_length = 0
2020-03-04 22:07:23 +01:00
for segment in line.split(","):
direction = segment[0]
length = int(segment[1:])
for _ in range(length):
if direction == "R":
x += 1
elif direction == "U":
y += 1
elif direction == "L":
x -= 1
elif direction == "D":
y -= 1
else:
raise ValueError(f"Unknown direction: {direction}")
2020-03-04 22:12:59 +01:00
wire_length += 1
2020-03-04 22:07:23 +01:00
position = (x, y)
2020-03-04 22:12:59 +01:00
if position not in seen_positions[wire]:
seen_positions[wire][position] = wire_length
steps = already_seen_on_others(seen_positions, wire, position)
if steps:
distances.add(steps + seen_positions[wire][position])
2020-03-04 22:07:23 +01:00
print(min(distances))
if __name__ == "__main__":
main()