Skip to content

Instantly share code, notes, and snippets.

@gnyman
Created December 10, 2022 12:11
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/16eb117eded5902c2f7dba4b2d0b54b2 to your computer and use it in GitHub Desktop.
Save gnyman/16eb117eded5902c2f7dba4b2d0b54b2 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)
# 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
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):
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)
# check if the tail is still adjacent to the head, and move it if necessary
if abs(head[0] - tail[0]) > 1 or abs(head[1] - tail[1]) > 1:
if direction == "R":
tail = (head[0] - 1, head[1])
elif direction == "L":
tail = (head[0] + 1, head[1])
elif direction == "U":
tail = (head[0], head[1] - 1)
elif direction == "D":
tail = (head[0], head[1] + 1)
# add the position of the tail to the set of tail positions
tail_positions.add(tail)
# print the final positions of the head and tail, and the number of unique positions visited by the tail
print("Final position of the head:", head)
print("Final position of the tail:", tail)
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