Solution to problem 3 part 1 in Python

This commit is contained in:
David Doblas Jiménez 2022-02-09 16:54:24 +01:00
parent ca33d9a723
commit 12c2c31aa4

View File

@ -57,23 +57,28 @@
# What is the Manhattan distance from the central port to the closest
# intersection?
with open("files/test.txt") as f:
from math import inf
from typing import List
from sympy import Segment
with open("files/P3.txt") as f:
wire_a, wire_b = [path.split(",") for path in f.read().strip().split()]
def get_final_point(init, direction, length):
if direction == "U":
def get_final_point(init: List[int], direction: str, length: int) -> List[int]:
if direction == "R":
init[0] += length
elif direction == "D":
init[0] -= length
elif direction == "R":
init[1] += length
elif direction == "L":
init[0] -= length
elif direction == "U":
init[1] += length
elif direction == "D":
init[1] -= length
return init
def get_path(wire):
def get_path(wire: List[str]) -> List[List[int]]:
init = [0, 0]
path = []
for step in wire:
@ -82,57 +87,29 @@ def get_path(wire):
# make a copy of the final point to avoid reference to same object
path.append(final_point.copy())
init = final_point
# add starting point
return [[0, 0]] + path
return path
# print(len(get_path(wire_a)))
# print(len(get_path(wire_b)))
def line(p1, p2):
A = p1[1] - p2[1]
B = p2[0] - p1[0]
C = p1[0] * p2[1] - p2[0] * p1[1]
return A, B, -C
def intersection(L1, L2):
D = L1[0] * L2[1] - L1[1] * L2[0]
Dx = L1[2] * L2[1] - L1[1] * L2[2]
Dy = L1[0] * L2[2] - L1[2] * L2[0]
if D != 0:
x = Dx // D
y = Dy // D
return x, y
else:
return False
# L1 = line([10,1003], [476,1003])
# L2 = line([250, 500], [250, 1200])
# R = intersection(L1, L2)
# if R:
# print(f"Intersection detected at {R}")
# else:
# print("No single intersection point detected")
path_a = get_path(wire_a)
print(path_a[:5])
path_b = get_path(wire_b)
print(path_b[:5])
for p1_a, p2_a, p1_b, p2_b in zip(
path_a[:-1], path_a[1:], path_b[:-1], path_b[1:]
):
# for idx_b, (p1_b, p2_b) in enumerate(zip(path_b[:-1], path_b[1:])):
line_a = line(p2_a, p1_a)
print(line_a)
line_b = line(p2_b, p1_b)
print(line_b)
R = intersection(line_a, line_b)
if R:
print(p1_a, p2_a, p1_b, p2_b)
break
def part_1() -> None:
closest = inf
for p1, p2 in zip(path_a[:-1], path_a[1:]):
s1 = Segment(p1, p2)
for p3, p4 in zip(path_b[:-1], path_b[1:]):
s2 = Segment(p3, p4)
intersect = s1.intersection(s2)
if intersect:
manhattan_distance = abs(intersect[0][0]) + abs(
intersect[0][1]
)
if manhattan_distance < closest:
closest = manhattan_distance
print(f"The manhattan distance to the closest intersection is {closest}")
if __name__ == "__main__":
part_1()