Skip to content

Instantly share code, notes, and snippets.

@gnyman
Created December 10, 2022 11:43
Embed
What would you like to do?
# Parse the input
with open('sample.txt') as f:
moves = [line.strip() for line in f]
# Initialize the head and tail positions
head_pos = [0, 0]
tail_pos = [0, 0]
# Keep track of the positions the tail has visited
visited = set()
visited.add((0, 0))
# Define a function to move the head and update the tail position
def movef(direction, steps):
global head_pos, tail_pos, visited
print(f"move:{direction} s:{steps}")
# Update the head position
if direction == 'U':
head_pos[1] += steps
elif direction == 'D':
head_pos[1] -= steps
elif direction == 'L':
head_pos[0] -= steps
elif direction == 'R':
head_pos[0] += steps
# Update the tail position
if head_pos[0] == tail_pos[0]:
# Tail moves vertically
if head_pos[1] > tail_pos[1]:
tail_pos[1] += 1
else:
tail_pos[1] -= 1
elif head_pos[1] == tail_pos[1]:
# Tail moves horizontally
if head_pos[0] > tail_pos[0]:
tail_pos[0] += 1
else:
tail_pos[0] -= 1
else:
# Tail moves diagonally
if head_pos[0] > tail_pos[0]:
tail_pos[0] += 1
else:
tail_pos[0] -= 1
if head_pos[1] > tail_pos[1]:
tail_pos[1] += 1
else:
tail_pos[1] -= 1
# Add the new tail position to the set of visited positions
visited.add((tail_pos[0], tail_pos[1]))
print(f"{head_pos},{tail_pos}")
# Loop through the moves and apply them
for move in moves:
direction = move[0]
steps = int(move[1:])
movef(direction, steps)
# Print the number of unique positions the tail visited
print(len(visited))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment