i am going back and doing old advents of code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
aoc_2022/day09/day09b.py

53 lines
1.3 KiB

10 months ago
import re
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("filename", help="the file from which to take data")
args = parser.parse_args()
with open(args.filename, "r") as f: commands = f.readlines()
visited = {(0,0)}
head = (0, 0)
tails = [(0, 0)]*9
def walk(command, head, tails, visited):
direction, repeats = command.split(" ")
repeats = int(repeats)
first = True
while repeats > 0:
head = step(direction, head)
for i in range(len(tails)):
if i==0:
h = head
else:
h = tails[i-1]
tails[i] = follow(h, tails[i])
first = False
visited = visited | {tails[-1]}
repeats -= 1
return head, tails, visited
def follow(head, tail):
if head[0] < tail[0]-1 or head[0] > tail[0]+1 or \
head[1] < tail[1]-1 or head[1] > tail[1]+1:
if head[0] < tail[0]: tail = (tail[0]-1, tail[1])
if head[0] > tail[0]: tail = (tail[0]+1, tail[1])
if head[1] < tail[1]: tail = (tail[0], tail[1]-1)
if head[1] > tail[1]: tail = (tail[0], tail[1]+1)
return tail
def step(direction, head):
match direction:
case 'R': return (head[0]+1, head[1])
case 'L': return (head[0]-1, head[1])
case 'U': return (head[0], head[1]+1)
case 'D': return (head[0], head[1]-1)
case _: return head
for command in commands:
head, tails, visited = walk(command, head, tails, visited)
print("visited {} locations".format(len(visited)))