Advent of code

 15 décembre 2024 

  Warehouse Woes : Déplacer des caisses façon sokoban, mais avec des caisses prenant deux places en largeur.
##########  ###
   
##.#...OO#  O.#
   
#O#O.....O  ..#
   
        ⋮   
#..O.O.O..  #O#
   
#.....O.OO  OO#
   
##########  ###
   
  
   
<v><v><>  
   
>^><<>vv  
   
        
Toute petite optimisation possible (qui ne fait gagner aucun temps) quand on touche une boîte horizontalement : s'occuper directement de la partie non touchée, qu'on sait être derrière.
  1. code_part_1_2.py
  2. code_part1_simple_affichageConsole.py
  3. code_part2_affichageConsole.py
  4. diff_adaptationAlgo_2_PourPartie_1.diffy
  5. diff_optimPushingHorizontally.diffy
  6. affichage_console_partie1.png
  7. affichage_console_partie2.png
  8. Visualisation superbe sur YouTube En 3D avec images réalistes et faite par Paul Bonsma
with open("input.txt", 'r', encoding='utf-8') as f:
    lines = [line[:-1] for line in f.readlines()]

sep = lines.index("")
grid1 = [list(line) for line in lines[:sep]]
grid2 = [line[:] for line in grid1]   # deep copy
instructions = ''.join(lines[sep+1:])

# change grid2
for y,line in enumerate(grid2):
    new_line = []
    for c in line:
        if c in '#.':
            new_line.extend(2*[c])
        elif c == '@':
            new_line.extend(['@','.'])
        else:
            new_line.extend(['[',']'])
    grid2[y] = new_line
        

DIRECTIONS = {'>':(1,0), '<':(-1,0), 'v':(0,1), '^':(0,-1)}

def find_start(grid):
    y = next(y for y,line in enumerate(grid) if '@' in line)
    x = grid[y].index('@')
    return x, y
x1, y1 = find_start(grid1)
x2, y2 = find_start(grid2)

# Far better functions in code_part1.py and code_part2.py !
def print_grid(grid):
    pad = '' if len(grid[0]) > 80 else ' '
    for line in grid:
        print(''.join(c + pad for c in line))


##### DÉBUT ALGO #####  # algo 2e partie un peu overkill pour partie 1, mais marche avec adaptation pour 'O'
def next_grid(grid, x, y, depl_x, depl_y):
    ### Find what needs to move
    pushed = set()
    todo = set([(x, y)])
    while todo:
        bx, by = todo.pop()
        pushed.add( (bx,by) )
        nx, ny = bx + depl_x, by + depl_y
        if (nx,ny) in pushed or (nx,ny) in todo:
            continue
        next_c = grid[ny][nx]
        if next_c == '#':
            return None      # Obstacle ! Nothing to do, return None to signal it.
        elif next_c in '[]O':
            todo.add( (nx, ny) )      # Always process the touched part of the box
            if next_c in '[]':            # If box has two parts
                if not depl_y:              # If pushing horizontally
                    todo.add( (bx+2*depl_x, by) )  # process other part
                elif next_c == '[':         # If pushing vertically on the left
                    todo.add( (bx+1,ny) )   #      process the right part of the box
                else:                       # If pushing vertically on the right
                    todo.add( (bx-1,ny) )   #      process the left part

    ### And push everything!
    grid_n = [line[:] for line in grid]
    for bx,by in pushed:
        grid_n[by][bx] = '.'
    for bx,by in pushed:
        grid_n[by+depl_y][bx+depl_x] = grid[by][bx]
    return grid_n

text_response = {}
for part, grid, x, y in (('partie 1', grid1, x1, y1), ('partie 2', grid2, x2, y2)):
    print_grid(grid)

    for i,instruction in enumerate(instructions):
        depl_x, depl_y = DIRECTIONS[instruction]
        new_grid = next_grid(grid, x, y, depl_x, depl_y)
        if new_grid:
            grid = new_grid
            x, y = x + depl_x, y + depl_y
    
    print_grid(grid)
    
    text_response[f"Réponse {part}:"] = sum( 100*y + x 
                                             for y in range(len(grid))
                                             for x in range(len(grid[0]))
                                             if grid[y][x] in '[O' )
    print('\n'.join(f"{txt} {rep}" for txt,rep in text_response.items()))