My Advent of Code solutions in Python.
kevinyap.ca/2019/12/going-fast-in-advent-of-code/
advent-of-code
python
1import fileinput
2from utils import Point
3
4
5def sign(x, y):
6 if x > y:
7 return 1
8 elif x < y:
9 return -1
10 else:
11 return 0
12
13
14def update(head, tail):
15 """
16 Given the current position of head and tail,
17 return the new tail position.
18 """
19
20 # This occurs if we have moved diagonally away from the tail,
21 # and it is far enough for the tail to come and chase us.
22 if abs(head.x - tail.x) + abs(head.y - tail.y) > 2:
23 tail += Point(sign(head.x, tail.x), sign(head.y, tail.y))
24
25 # Check if we need to move horizontally/vertically.
26 elif (head.x == tail.x or head.y == tail.y) and (abs(head.x - tail.x) + abs(head.y - tail.y) > 1):
27 tail += Point(sign(head.x, tail.x), sign(head.y, tail.y))
28
29 return tail
30
31
32mapping = {
33 "U": Point(0, 1),
34 "R": Point(1, 0),
35 "D": Point(0, -1),
36 "L": Point(-1, 0),
37}
38
39INSTRUCTIONS = [line.strip() for line in fileinput.input()]
40
41# Solve problem.
42for part, bridge_len in ((1, 2), (2, 10)):
43 bridge = [Point(0, 0) for _ in range(bridge_len)]
44 seen = set()
45
46 for line in INSTRUCTIONS:
47 d, amt = line.split()
48 amt = int(amt)
49
50 for _ in range(amt):
51 # First, move the head in the given direction.
52 bridge[0] += mapping[d]
53 for i in range(1, bridge_len):
54 bridge[i] = update(bridge[i-1], bridge[i])
55 seen.add(bridge[-1])
56
57 print(f"Part {part}: {len(seen)}")
58