day 9 python part 1

main
magical 2022-12-08 21:13:53 -08:00
parent 383ff93502
commit 036a563d8f
3 changed files with 2058 additions and 0 deletions

50
day09/day09.py 100644
View File

@ -0,0 +1,50 @@
H = (0,0)
T = (0,0)
def go(p, dir):
x,y = p
if dir == "U":
y += 1
if dir == "D":
y -= 1
if dir == "L":
x -= 1
if dir == "R":
x += 1
return x,y
def follow():
if H == T:
return T
if abs(H[0] - T[0]) <= 1 and abs(H[1] - T[1]) <= 1:
return T
if H[1] == T[1]:
x,y = T
x = H[0] - sgn(H[0] - T[0])
return x,y
if H[0] == T[0]:
x,y = T
y = H[1] - sgn(H[1]-T[1])
return x,y
# diagonal
x,y = T
x += sgn(H[0] - T[0])
y += sgn(H[1] - T[1])
return x,y
def sgn(x):
if x==0: return 0
if x > 0: return 1
return -1
visited = set([T])
for line in open("input"):
dir, count = line.split()
count = int(count)
for _ in range(count):
H = go(H, dir)
T = follow()
visited.add(T)
print(H,T)
print(len(visited))

2000
day09/input 100644

File diff suppressed because it is too large Load Diff

8
day09/sample 100644
View File

@ -0,0 +1,8 @@
R 4
U 4
L 3
D 1
R 4
D 1
L 5
R 2