Autor Tema: Advent of code, solución día 5

0 Usuarios y 1 Visitante están viendo este tema.

05 Diciembre, 2022, 12:07 pm
Leído 652 veces

geómetracat

  • Moderador Global
  • Mensajes: 4,065
  • País: es
  • Karma: +0/-0
  • Sexo: Masculino
Hola a todos,

Los enunciados del día 5 (Supply Stacks) son los siguientes:
Parte 1:
Spoiler
The expedition can depart as soon as the final supplies have been unloaded from the ships. Supplies are stored in stacks of marked crates, but because the needed supplies are buried under many other crates, the crates need to be rearranged.

The ship has a giant cargo crane capable of moving crates between stacks. To ensure none of the crates get crushed or fall over, the crane operator will rearrange them in a series of carefully-planned steps. After the crates are rearranged, the desired crates will be at the top of each stack.

The Elves don't want to interrupt the crane operator during this delicate procedure, but they forgot to ask her which crate will end up where, and they want to be ready to unload them as soon as possible so they can embark.

They do, however, have a drawing of the starting stacks of crates and the rearrangement procedure (your puzzle input). For example:

    [D]   
[N] [C]   
[Z] [M] [P]
 1   2   3

move 1 from 2 to 1
move 3 from 1 to 3
move 2 from 2 to 1
move 1 from 1 to 2

In this example, there are three stacks of crates. Stack 1 contains two crates: crate Z is on the bottom, and crate N is on top. Stack 2 contains three crates; from bottom to top, they are crates M, C, and D. Finally, stack 3 contains a single crate, P.

Then, the rearrangement procedure is given. In each step of the procedure, a quantity of crates is moved from one stack to a different stack. In the first step of the above rearrangement procedure, one crate is moved from stack 2 to stack 1, resulting in this configuration:

[D]       
[N] [C]   
[Z] [M] [P]
 1   2   3

In the second step, three crates are moved from stack 1 to stack 3. Crates are moved one at a time, so the first crate to be moved (D) ends up below the second and third crates:

        [Z]
        [N]
    [C] [D]
    [M] [P]
 1   2   3

Then, both crates are moved from stack 2 to stack 1. Again, because crates are moved one at a time, crate C ends up below crate M:

        [Z]
        [N]
[M]     [D]
[C]     [P]
 1   2   3

Finally, one crate is moved from stack 1 to stack 2:

        [Z]
        [N]
        [D]
[C] [M] [P]
 1   2   3

The Elves just need to know which crate will end up on top of each stack; in this example, the top crates are C in stack 1, M in stack 2, and Z in stack 3, so you should combine these together and give the Elves the message CMZ.

After the rearrangement procedure completes, what crate ends up on top of each stack?
[cerrar]
Parte 2:
Spoiler
As you watch the crane operator expertly rearrange the crates, you notice the process isn't following your prediction.

Some mud was covering the writing on the side of the crane, and you quickly wipe it away. The crane isn't a CrateMover 9000 - it's a CrateMover 9001.

The CrateMover 9001 is notable for many new and exciting features: air conditioning, leather seats, an extra cup holder, and the ability to pick up and move multiple crates at once.

Again considering the example above, the crates begin in the same configuration:

    [D]   
[N] [C]   
[Z] [M] [P]
 1   2   3

Moving a single crate from stack 2 to stack 1 behaves the same as before:

[D]       
[N] [C]   
[Z] [M] [P]
 1   2   3

However, the action of moving three crates from stack 1 to stack 3 means that those three moved crates stay in the same order, resulting in this new configuration:

        [D]
        [N]
    [C] [Z]
    [M] [P]
 1   2   3

Next, as both crates are moved from stack 2 to stack 1, they retain their order as well:

        [D]
        [N]
[C]     [Z]
[M]     [P]
 1   2   3

Finally, a single crate is still moved from stack 1 to stack 2, but now it's crate C that gets moved:

        [D]
        [N]
        [Z]
[M] [C] [P]
 1   2   3

In this example, the CrateMover 9001 has put the crates in a totally different order: MCD.

Before the rearrangement process finishes, update your simulation so that the Elves know where they should stand to be ready to unload the final supplies. After the rearrangement procedure completes, what crate ends up on top of each stack?
[cerrar]

Mi solución en Python:
Código: [Seleccionar]
from copy import deepcopy

with open("input5.txt") as f:
    inp = f.read()

head, moves = inp.split("\n\n")

# Parse the stacks of crates
head = head.splitlines()[::-1]
keys_positions = {x:int(y) for (x,y) in enumerate(head[0]) if y != ' '}
stacks = {i:[] for i in keys_positions.values()}
for line in head[1:]:
    for pos in keys_positions:
        if line[pos] not in ' []':
            stacks[keys_positions[pos]].append(line[pos])

# Parse the moves
moves = moves.splitlines()
move_list = [(int(move[1]), int(move[3]), int(move[5])) for move in [x.split() for x in moves]]

# Part 1
def move_crates1(stacks, move):
    for i in range(move[0]):
        crate = stacks[move[1]].pop()
        stacks[move[2]].append(crate)
    return stacks

stacks1 = deepcopy(stacks)
for move in move_list:
    stacks1 = move_crates1(stacks1, move)
print(''.join([stack[-1] for stack in stacks1.values()]))

# Part 2
def move_crates2(stacks, move):
    crates = stacks[move[1]][-move[0]:]
    stacks[move[1]] = stacks[move[1]][:-move[0]]
    stacks[move[2]] += crates
    return stacks

stacks2 = deepcopy(stacks)
for move in move_list:
    stacks2 = move_crates2(stacks2, move)
print(''.join([stack[-1] for stack in stacks2.values()]))

Seguimos con problemas facilitos. En este he tardado más en pensar un parser general para leer el input que en resolver ambas partes.
La ecuación más bonita de las matemáticas: \( d^2=0 \)

05 Diciembre, 2022, 09:41 pm
Respuesta #1

Eparoh

  • $$\Large \color{#c88359}\pi\,\pi\,\pi\,\pi$$
  • Mensajes: 981
  • País: es
  • Karma: +0/-0
  • Sexo: Masculino
Hola, ¡aun llego a tiempo!  :laugh:

Mi solución en Maple y Excel:

Código: [Seleccionar]
Stacks:=proc(File)
   local s, l, n, R, i, t, cont;
      s:=FileTools[Text][ReadLine](File);
      l:=length(s);
      n:=(l+1)/4; #Número de stacks
      R:=[seq("",i=1..n)];
      cont:=1;
      while s[1..2] <> " 1" do
         for i from 2 to l by 4 do
            t:=s[i];
            if t <> " " then
               R[((i-2)/4)+1]:=cat(R[((i-2)/4)+1],t);
            fi;
         od;
         s:=FileTools[Text][ReadLine](File);
         cont:=cont+1;
      od;
      FileTools[Text][Close](File);
   RETURN([R,cont+2]);
end:

F:=Stacks(cat(currentdir(),"\\Template 5.txt")):
Mont_0:=F[1]:
Instruc:=readdata(cat(currentdir(),"\\Template 5.txt"),[string,string,string,string,string,string])[F[2]-1..][..,[2,4,6]]:

Mov:=proc(M,L,n)
   local R;
      R:=M;
      R[L[2]]:=M[L[2]][L[1]+1..];
      if n=1 then
         R[L[3]]:=cat(StringTools[Reverse](M[L[2]][1..L[1]]),M[L[3]]);
      else
         R[L[3]]:=cat(M[L[2]][1..L[1]],M[L[3]]);
      fi;
   RETURN(R);
end:

Mov_total:=proc(M,F,n)
   local N, R, i;
      N:=nops(F);
      R:=M;
      for i from 1 to N do
         R:=Mov(R,map(parse,F[i]),n);
      od;
   RETURN(R);
end:

Primeras:=proc(M)
   local N, R, i;
      N:=nops(M);
      R:="";
      for i from 1 to N do
         R:=cat(R,M[i][1]);
      od;
   RETURN(R);
end:

Primeras(Mov_total(Mont_0,Instruc,1));
Primeras(Mov_total(Mont_0,Instruc,2));

Seguimos con problemas facilitos. En este he tardado más en pensar un parser general para leer el input que en resolver ambas partes.

En mi código lo más largo es también sacar los datos del txt de forma general  :laugh: :laugh:

Aunque hoy me pasó una cosa curiosa. Tuve una idea de transformar el problema en una matriz enorme y resolverlo a través de ciertas operaciones aplicadas a esa matriz y me pasé un par de horas para conseguir eso. Después, lo intenté resolver en Excel y me di cuenta de que se podia hacer infinitamente más fácil con la idea que use en Excel, y esa es la versión que pongo (que creo que en esencia hago lo mismo que tu, pero no estoy del todo seguro porque me pierde un poco la sintaxis de python)  ::)

Un saludo.

PD: En el archivo de Excel de hoy tuve que "hacer trampas" y utilizar una función VBA porque con mi excel antiguo creo que es imposible revertir el orden de una cadena de texto de otra forma (al menos de manera generalizable). El archivo lo subo en .rar, porque el foro no admite la extensión .xslm.

06 Diciembre, 2022, 05:05 pm
Respuesta #2

w a y s

  • $$\Large \color{#5e8d56}\pi\,\pi\,\pi$$
  • Mensajes: 256
  • País: es
  • Karma: +0/-0
  • Sexo: Masculino
  • I
Hola,

es verdad que el problema era muy fácil, sin embargo no se me ha ocurrido nada para parsear la entrada de las cajas, para poder resolverlo la he cambiado para que me fuera más fácil leerlo, no sé si eso está permitido o no, sea como sea, ahí va mi solución en java:

Código: [Seleccionar]
package aoc_2022;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;
import java.util.Stack;
import java.util.TreeMap;

public class Day5 {
    private static final File CRATES_INPUT = new File("2022_inputs/2022_day5_input_1.txt");;
    private static final File INPUT = new File("2022_inputs/2022_day5_input.txt");
    private Map<Integer, Stack<Character>> crates;

    Day5(){
        crates = new TreeMap<>();
    }

    private void generateMap(){
        String line = "";
        try(BufferedReader br = new BufferedReader(new FileReader(CRATES_INPUT))){
            while((line = br.readLine()) != null){
                int index = Integer.parseInt(line.charAt(0)+"");
                line = line.replaceAll(" ","");
                crates.put(index,new Stack<>());
                for (int i = 1; i < line.length(); i++) {
                    crates.get(index).add(line.charAt(i));
                }
            }
        }catch(IOException e){
            System.err.println("Error generating map.");
        }
    }

    private void move(int move, int f, int t){ //part 1
        for (int i = 0; i < move; i++) {
            char crate = crates.get(f).pop();
            crates.get(t).push(crate);
        }
    }

    private void moveMoreThanOne(int move, int f, int t){ // added for part 2
        String crateOrder = "";
        for (int i = 0; i < move; i++) {
            crateOrder += crates.get(f).pop();
        }
        for (int i = crateOrder.length()-1; i >= 0; i--) {
            crates.get(t).push(crateOrder.charAt(i));
        }
    }

    private void solve(){
        String line = "";
        try(BufferedReader br = new BufferedReader(new FileReader(INPUT))){
            while((line = br.readLine())!= null){
                String [] x = line.split(" ");
                int numberOfMoves = Integer.parseInt(x[1]);
                if(numberOfMoves > 1 )
                    moveMoreThanOne(numberOfMoves,Integer.parseInt(x[3]),Integer.parseInt(x[5]));
                else
                    move(numberOfMoves,Integer.parseInt(x[3]),Integer.parseInt(x[5]));
            }
        }catch (IOException e){
            System.err.println("Error reading input.");
        }
    }

    private String getAnswer(){
        String answer = "";
        for (int i = 1; i <= 9 ; i++) {
            answer += crates.get(i).pop();
        }
        return answer;
    }

    public static void main(String[] args) {
        Day5 d5 = new Day5();
        d5.generateMap();
        d5.solve();
        System.out.println(d5.getAnswer());
    }
}



06 Diciembre, 2022, 06:05 pm
Respuesta #3

Eparoh

  • $$\Large \color{#c88359}\pi\,\pi\,\pi\,\pi$$
  • Mensajes: 981
  • País: es
  • Karma: +0/-0
  • Sexo: Masculino
Hola.

Hola,

es verdad que el problema era muy fácil, sin embargo no se me ha ocurrido nada para parsear la entrada de las cajas, para poder resolverlo la he cambiado para que me fuera más fácil leerlo, no sé si eso está permitido o no, sea como sea, ahí va mi solución en java:

Bueno, permitido o no en estas cosas supongo que es lo que cada uno quiera :laugh:

Un saludo.