◂ 9 décembre 2022 ▸
Rope Bridge : Corde qui bouge et tire la queue (snake)
L 2
D 2
L 2
R 2
L 1
⋮
- code.py
- snake.png
- snake.py
DIRECTIONS = {'R':(1,0), 'L':(-1,0), 'U':(0,1), 'D':(0,-1)}
f = open("input.txt", 'r')
splittedLines = [line[:-1].split() for line in f.readlines()]
commands = map( lambda t:{'direction':DIRECTIONS[t[0]], 'nb':int(t[1])}, splittedLines)
def sign(x): # ou utiliser numpy.sign
return (x > 0 and 1) or (x < 0 and -1) or 0
# Version pour écarts d'au plus 2 entre deux bouts:
def updatePositionSimple(xHead, yHead, xTail, yTail):
diffX = xHead - xTail
diffY = yHead - yTail
if (abs(diffX) <= 1) and (abs(diffY) <= 1):
return (xTail, yTail)
else:
return (xTail + sign(diffX), yTail + sign(diffY))
# Version généralisée pour tout écart entre deux bouts:
def updatePosition(xHead, yHead, xTail, yTail):
diffX = xHead - xTail
diffY = yHead - yTail
return (xTail + diffX - sign(diffX)*(abs(diffX) >= abs(diffY)), yTail + diffY - sign(diffY)*(abs(diffY) >= abs(diffX)))
positions = 10 * [ (0,0) ]
# Partie 1
visitedT = { (0,0) }
# Partie 2
visited9 = { (0,0) }
for command in commands:
for _ in range(command['nb']):
positions[0] = ( positions[0][0] + command['direction'][0], positions[0][1] + command['direction'][1] )
for i in range(1, len(positions)):
positions[i] = updatePosition(*positions[i-1], *positions[i])
visitedT.add(positions[1])
visited9.add(positions[-1])
print("Réponse partie 1:", len(visitedT))
print("Réponse partie 2:", len(visited9))