-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day9.py
43 lines (37 loc) · 1.32 KB
/
Day9.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
from helpers.importHelpers import *
def getNormalizedDistance(distance):
if distance == 0:
return 0
return distance/abs(distance)
def getTailPosition(oldTailPos, headPos):
diffX = headPos[0] - oldTailPos[0]
diffY = headPos[1] - oldTailPos[1]
if abs(diffX) <= 1 and abs(diffY) <= 1:
return oldTailPos
diffX = getNormalizedDistance(diffX)
diffY = getNormalizedDistance(diffY)
return (oldTailPos[0] + diffX, oldTailPos[1] + diffY)
def getVisitedPositions(stringInput, ropeLength):
knots = [(0,0)] * ropeLength #knots[0] is the head, knots[-1] is the tail
visitedPositions = set()
for line in stringInput.split("\n"):
direction, distance = line.split(" ")
distance = int(distance)
match direction:
case "R":
diffX, diffY = 1, 0
case "L":
diffX, diffY = -1, 0
case "U":
diffX, diffY = 0, 1
case "D":
diffX, diffY = 0, -1
for _ in range(distance):
knots[0] = (knots[0][0] + diffX, knots[0][1] + diffY) #move head
for i in range(1, len(knots)): #move tail accordingly
knots[i] = getTailPosition(knots[i], knots[i-1])
visitedPositions.add(knots[-1])
return(len(visitedPositions))
stringInput = getInput()
print("Part 1: ", getVisitedPositions(stringInput, 2))
print("Part 2: ", getVisitedPositions(stringInput, 10))