Skip to content

Instantly share code, notes, and snippets.

@mattmess1221
Last active December 3, 2019 22:08
Show Gist options
  • Save mattmess1221/14b2836b832509b21d4167d5c5248629 to your computer and use it in GitHub Desktop.
Save mattmess1221/14b2836b832509b21d4167d5c5248629 to your computer and use it in GitHub Desktop.
import aoc
from typing import NamedTuple
class Point(NamedTuple):
x: int
y: int
def up(self, distance):
for p in range(1, distance + 1):
yield Point(self.x, self.y + p)
def down(self, distance):
for p in range(1, distance + 1):
yield Point(self.x, self.y - p)
def right(self, distance):
for p in range(1, distance + 1):
yield Point(self.x + p, self.y)
def left(self, distance):
for p in range(1, distance + 1):
yield Point(self.x - p, self.y)
def main():
with aoc.open_input(__name__) as f:
line1 = f.readline().split(',')
line2 = f.readline().split(',')
execute(line1, line2)
def test():
test0 = ["R8,U5,L5,D3", "U7,R6,D4,L4"]
execute(*(line.split(',') for line in test0))
test1 = ["R75,D30,R83,U83,L12,D49,R71,U7,L72", "U62,R66,U55,R34,D71,R55,D58,R83"]
execute(*(line.split(',') for line in test1))
test2 = ["R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51", "U98,R91,D20,R16,D67,R40,U7,R15,U6,R7"]
execute(*(line.split(',') for line in test2))
def run_path(line):
last_point = Point(0, 0)
path = []
visited = {}
i = 0
for dir in line:
vec, dist = dir[0], int(dir[1:])
if vec == 'U':
points = last_point.up(dist)
elif vec == 'D':
points = last_point.down(dist)
elif vec == 'L':
points = last_point.left(dist)
elif vec == 'R':
points = last_point.right(dist)
else:
raise Exception("Unknown direction " + vec)
for p in points:
i += 1
if p not in visited:
visited[p] = i
path.append(p)
last_point = path[len(path) - 1]
return set(path), visited
def calculate_interceptions(line1, line2):
path1, visited1 = run_path(line1)
path2, visited2 = run_path(line2)
path_intersect = path1.intersection(path2)
return path_intersect, visited1, visited2
def execute(line1, line2):
intercepts, v1, v2 = calculate_interceptions(line1, line2)
def distance(p):
return abs(p.x) + abs(p.y)
def speed(p):
return v1[p] + v2[p]
closest_point = min(intercepts, key=distance)
print("Closest:", closest_point, "distance:", distance(closest_point), "speed:", speed(closest_point))
fastest_point = min(intercepts, key=speed)
print("Fastest:", fastest_point, "distance:", distance(fastest_point), "speed:", speed(fastest_point))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment