adventofcode2024/day15/sol.py

59 lines
1.2 KiB
Python

def parse(file):
map = []
for line in file:
line = line.strip()
if not line:
break
map.append(line)
moves = ""
for line in file:
moves += line.strip().replace("&lt;","<").replace("&gt;",">")
return map, moves
def solve(file):
map, moves = parse(file)
map = [list(x) for x in map]
for y,line in enumerate(map):
if '@' in line:
x = line.index('@')
cur = y,x
print(moves)
for m in moves:
next, ok = move(map, cur, m)
cur = next
print(cur)
t = 0
for y,line in enumerate(map):
for x,c in enumerate(line):
if c == 'O':
t += y*100 + x
print("".join(line))
print(t)
def move(map, cur, m):
if m == 'v': d = (0,1)
if m == '<': d = (-1,0)
if m == '>': d = (1,0)
if m == '^': d = (0,-1)
n = (cur[0]+d[0], cur[1]+d[1])
c = map[n[1]][n[0]]
if c == 'O':
_, ok = move(map, n, m)
if not ok:
return cur, False
elif c == '#':
return cur, False
map[n[1]][n[0]] = map[cur[1]][cur[0]]
map[cur[1]][cur[0]] = '.'
return n, True
solve(open("sample1.in"))
solve(open("sample2.in"))
solve(open("input"))