advent24-llm / day15 /solution_gemini-1.5-pro.py
jerpint's picture
Add solution files
a4da721
raw
history blame
3.21 kB
def solve():
file = "input.txt"
with open(file, 'r') as f:
lines = f.readlines()
grid = [list(line.strip()) for line in lines[:-2]]
moves = lines[-1].strip()
def get_robot_pos(grid):
for r in range(len(grid)):
for c in range(len(grid[0])):
if grid[r][c] == '@':
return r, c
def is_valid(r, c, grid):
return 0 <= r < len(grid) and 0 <= c < len(grid[0]) and grid[r][c] != '#'
def move(grid, dr, dc):
r, c = get_robot_pos(grid)
nr, nc = r + dr, c + dc
if is_valid(nr, nc, grid):
if grid[nr][nc] == 'O':
nnr, nnc = nr + dr, nc + dc
if is_valid(nnr, nnc, grid) and grid[nnr][nnc] == '.':
grid[nnr][nnc] = 'O'
grid[nr][nc] = '@'
grid[r][c] = '.'
elif grid[nr][nc] == '.':
grid[nr][nc] = '@'
grid[r][c] = '.'
return grid
for move_char in moves:
if move_char == '^':
grid = move(grid, -1, 0)
elif move_char == 'v':
grid = move(grid, 1, 0)
elif move_char == '<':
grid = move(grid, 0, -1)
elif move_char == '>':
grid = move(grid, 0, 1)
gps_sum = 0
for r in range(len(grid)):
for c in range(len(grid[0])):
if grid[r][c] == 'O':
gps_sum += (r * 100) + c
print(str(gps_sum))
# Part 2
grid2 = [list(line.strip()) for line in lines[:-2]]
grid2 = [[c * 2 for c in row] for row in grid2]
for r in range(len(grid2)):
for c in range(len(grid2[0])):
if grid2[r][c] == 'O':
grid2[r][c] = '['
grid2[r][c+1] = ']'
elif grid2[r][c] == '@':
grid2[r][c+1] = '.'
def move2(grid, dr, dc):
r, c = get_robot_pos(grid)
nr, nc = r + dr, c + dc
if is_valid(nr, nc, grid):
if grid[nr][nc] == '[':
nnr, nnc = nr + dr, nc + dc
if is_valid(nnr, nnc, grid) and grid[nnr][nnc] == '.':
if is_valid(nnr, nnc + 1, grid) and grid[nnr][nnc + 1] == '.':
grid[nnr][nnc] = '['
grid[nnr][nnc + 1] = ']'
grid[nr][nc] = '@'
grid[nr][nc + 1] = '.'
grid[r][c] = '.'
grid[r][c + 1] = '.'
elif grid[nr][nc] == '.':
grid[nr][nc] = '@'
grid[r][c] = '.'
if grid[r][c+1] == '.':
grid[r][c+1] = '.'
return grid
for move_char in moves:
if move_char == '^':
grid2 = move2(grid2, -1, 0)
elif move_char == 'v':
grid2 = move2(grid2, 1, 0)
elif move_char == '<':
grid2 = move2(grid2, 0, -1)
elif move_char == '>':
grid2 = move2(grid2, 0, 1)
gps_sum2 = 0
for r in range(len(grid2)):
for c in range(len(grid2[0])):
if grid2[r][c] == '[':
gps_sum2 += (r * 100) + c
print(str(gps_sum2))
solve()