Advertisement
Guest User

Untitled

a guest
Dec 15th, 2024
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.77 KB | None | 0 0
  1. # Input: grid of # O . @ (border all #)
  2. #        then blank line, then sequence of < ^ > v characters
  3. # Output: @ attempts to make those moves, pushing boxes (O),
  4. #         unless they would hit a wall (#) in case nothing moves
  5. #         then sum of (100 * row + column) over all boxes
  6.  
  7. robot_r, robot_c = -1, -1
  8.  
  9. def try_to_move():
  10.   global robot_r
  11.   global robot_c
  12.   new_r, new_c = robot_r + dr, robot_c + dc
  13.   if grid[new_r][new_c] == ".":
  14.     grid[robot_r][robot_c] = "."
  15.     grid[new_r][new_c] = "@"
  16.     robot_r, robot_c = new_r, new_c
  17.     return
  18.   if grid[new_r][new_c] == "#":
  19.     return
  20.   new_r2, new_c2 = new_r, new_c
  21.   while True:
  22.     new_r2 += dr
  23.     new_c2 += dc
  24.     if grid[new_r2][new_c2] == "#":
  25.       break
  26.     if grid[new_r2][new_c2] == ".":
  27.       grid[robot_r][robot_c] = "."
  28.       grid[new_r][new_c] = "@"
  29.       robot_r, robot_c = new_r, new_c
  30.       grid[new_r2][new_c2] = "O"
  31.       break
  32.   return
  33.  
  34. grid = []
  35. directions = ""
  36.  
  37. found_blank_line = False
  38. r = 0
  39. file = open("15_input.txt", "r")
  40. for line in file:
  41.   line = line.replace("\n", "")
  42.   if line == "":
  43.     found_blank_line = True
  44.     continue
  45.   if found_blank_line:
  46.     directions += line
  47.     continue
  48.   row = []
  49.   c = 0
  50.   for character in line:
  51.     row.append(character)
  52.     if character == "@":
  53.       robot_r, robot_c = r, c
  54.     c += 1
  55.   grid.append(row)
  56.   r += 1
  57.  
  58. for character in directions:
  59.   dr, dc = -2, -2
  60.   if character == "^":
  61.     dr, dc = -1, 0
  62.   if character == "v":
  63.     dr, dc = 1, 0
  64.   if character == "<":
  65.     dr, dc = 0, -1
  66.   if character == ">":
  67.     dr, dc = 0, 1
  68.   if dr == -2:
  69.     continue
  70.   try_to_move()
  71.  
  72. total = 0
  73. for r in range(len(grid)):
  74.   for c in range(len(grid[0])):
  75.     if grid[r][c] == "O":
  76.       total += 100 * r + c
  77. print (total)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement