Skip to content

Instantly share code, notes, and snippets.

@gnyman
Last active December 10, 2022 17:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gnyman/dc4620395d6d2d20df55b47240db6542 to your computer and use it in GitHub Desktop.
Save gnyman/dc4620395d6d2d20df55b47240db6542 to your computer and use it in GitHub Desktop.
# open the input file and read the lines
with open("input.txt") as f:
lines = f.readlines()
# initialize the head and tail at the same position
head = (0, 0)
tail = (0, 0)
# initialize the 10 parts of the rope
parts = [(0, 0) for _ in range(10)]
# parse the list of movements for the head from the input file
movements = [line.strip() for line in lines]
# create a set to store the positions visited by the tail (part 10)
tail_positions = set()
# iterate over the movements and update the position of the head and tail
for move in movements:
direction, steps = move.split()
steps = int(steps)
for i in range(steps):
# update the position of the head
if direction == "R":
head = (head[0] + 1, head[1])
elif direction == "L":
head = (head[0] - 1, head[1])
elif direction == "U":
head = (head[0], head[1] + 1)
elif direction == "D":
head = (head[0], head[1] - 1)
# update the position of the 10 parts of the rope
for i in range(9, 0, -1):
parts[i] = parts[i-1]
parts[0] = head
# add the position of the tail (part 10) to the set of tail positions
tail_positions.add(parts[-1])
print("Number of unique positions visited by the tail:", len(tail_positions))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment