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

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

Ayer a las 04:30 pm
Leído 44 veces

geómetracat

  • Moderador Global
  • Mensajes: 3,330
  • País: es
  • Karma: +0/-0
  • Sexo: Masculino
Los enunciados del día 3 (Rucksack Reorganization) son:

Parte 1:
Spoiler
One Elf has the important job of loading all of the rucksacks with supplies for the jungle journey. Unfortunately, that Elf didn't quite follow the packing instructions, and so a few items now need to be rearranged.

Each rucksack has two large compartments. All items of a given type are meant to go into exactly one of the two compartments. The Elf that did the packing failed to follow this rule for exactly one item type per rucksack.

The Elves have made a list of all of the items currently in each rucksack (your puzzle input), but they need your help finding the errors. Every item type is identified by a single lowercase or uppercase letter (that is, a and A refer to different types of items).

The list of items for each rucksack is given as characters all on a single line. A given rucksack always has the same number of items in each of its two compartments, so the first half of the characters represent items in the first compartment, while the second half of the characters represent items in the second compartment.

For example, suppose you have the following list of contents from six rucksacks:

vJrwpWtwJgWrhcsFMMfFFhFp
jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL
PmmdzqPrVvPwwTWBwg
wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn
ttgJtRGJQctTZtZT
CrZsJsPPZsGzwwsLwLmpwMDw

    The first rucksack contains the items vJrwpWtwJgWrhcsFMMfFFhFp, which means its first compartment contains the items vJrwpWtwJgWr, while the second compartment contains the items hcsFMMfFFhFp. The only item type that appears in both compartments is lowercase p.
    The second rucksack's compartments contain jqHRNqRjqzjGDLGL and rsFMfFZSrLrFZsSL. The only item type that appears in both compartments is uppercase L.
    The third rucksack's compartments contain PmmdzqPrV and vPwwTWBwg; the only common item type is uppercase P.
    The fourth rucksack's compartments only share item type v.
    The fifth rucksack's compartments only share item type t.
    The sixth rucksack's compartments only share item type s.

To help prioritize item rearrangement, every item type can be converted to a priority:

    Lowercase item types a through z have priorities 1 through 26.
    Uppercase item types A through Z have priorities 27 through 52.

In the above example, the priority of the item type that appears in both compartments of each rucksack is 16 (p), 38 (L), 42 (P), 22 (v), 20 (t), and 19 (s); the sum of these is 157.

Find the item type that appears in both compartments of each rucksack. What is the sum of the priorities of those item types?
[cerrar]

Parte 2:
Spoiler
As you finish identifying the misplaced items, the Elves come to you with another issue.

For safety, the Elves are divided into groups of three. Every Elf carries a badge that identifies their group. For efficiency, within each group of three Elves, the badge is the only item type carried by all three Elves. That is, if a group's badge is item type B, then all three Elves will have item type B somewhere in their rucksack, and at most two of the Elves will be carrying any other item type.

The problem is that someone forgot to put this year's updated authenticity sticker on the badges. All of the badges need to be pulled out of the rucksacks so the new authenticity stickers can be attached.

Additionally, nobody wrote down which item type corresponds to each group's badges. The only way to tell which item type is the right one is by finding the one item type that is common between all three Elves in each group.

Every set of three lines in your list corresponds to a single group, but each group can have a different badge item type. So, in the above example, the first group's rucksacks are the first three lines:

vJrwpWtwJgWrhcsFMMfFFhFp
jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL
PmmdzqPrVvPwwTWBwg

And the second group's rucksacks are the next three lines:

wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn
ttgJtRGJQctTZtZT
CrZsJsPPZsGzwwsLwLmpwMDw

In the first group, the only item type that appears in all three rucksacks is lowercase r; this must be their badges. In the second group, their badge item type must be Z.

Priorities for these items must still be found to organize the sticker attachment efforts: here, they are 18 (r) for the first group and 52 (Z) for the second group. The sum of these is 70.

Find the item type that corresponds to the badges of each three-Elf group. What is the sum of the priorities of those item types?
[cerrar]

Mi solución en Python:
Código: [Seleccionar]
with open("input3.txt") as f:
    rucksacks = f.read().splitlines()
   
letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
priority_dict = {let:(num+1) for num,let in dict(enumerate(letters)).items()}

# Part 1
compartments = [(x[:len(x)//2], x[len(x)//2:]) for x in rucksacks]
common_items = [set(x).intersection(set(y)).pop() for (x,y) in compartments]
print(sum([priority_dict[item] for item in common_items]))

# Part 2
rucksacks_sets = [set(x) for x in rucksacks]
groups = [rucksacks_sets[i:i+3] for i in range(0,len(rucksacks_sets), 3)]
badges = [x[0].intersection(x[1]).intersection(x[2]).pop() for x in groups]
print(sum([priority_dict[item] for item in badges]))

PD: Se nota que es fin de semana, he entrado en el foro pensando que alguien habría abierto el tema y parece que soy el primero.  ;D
La ecuación más bonita de las matemáticas: \( d^2=0 \)

Ayer a las 07:10 pm
Respuesta #1

Eparoh

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

PD: Se nota que es fin de semana, he entrado en el foro pensando que alguien habría abierto el tema y parece que soy el primero.  ;D

Yo lo hice esta mañana, pero nunca se si un problema es lo suficiente interesante como para compartirlo y espero a que otro haga el post :laugh:

Por lo que veo de nuevo tenemos prácticamente la misma solución, pero python es mucho más elegante (y, no se exactamente como funcionan los diccionarios, pero parecen ser muy útiles para estas cosas de formar funciones con dominio finito). Dejo mi solución en Maple:

Código: [Seleccionar]
F:=readdata(cat(currentdir(),"\\Template 3.txt"),string):

Str2Num:=proc(s)
   local N, R, i;
      N:=length(s);
      R:=[seq(StringTools[Ord](s[i]),i=1..N)];
      for i from 1 to N do
         if R[i]<91 then
            R[i]:=R[i]-38;
         else
            R[i]:=R[i]-96;
         fi;
      od;
   RETURN(R);
end:

Bolsas:=proc(s)
   local N, R, i;
      N:=length(s);
      R:=Str2Num(s);
   RETURN(convert(R[1..N/2],set) intersect convert(R[N/2+1..N],set));
end:

Grupos:=proc(S)
   local N, R, i;
      R:=[seq(Str2Num(S[i]),i=1..3)];
   RETURN(convert(R[1],set) intersect convert(R[2],set) intersect convert(R[3],set));
end:

Prioridades:=proc(F,n)
   if n=1 then
      RETURN(add(x, x in seq(Bolsas(F[i])[1],i=1..nops(F))));
   else
      RETURN(add(x, x in seq(Grupos(F[3*i+1..3*i+3])[1],i=0..(nops(F)/3)-1)));
   fi;
end:
 
Prioridades(F,1);
Prioridades(F,2);


También lo resolví en Excel a petición de un amigo (aunque es un monstruo de cuidado  ::)), lo adjunto por si alguien tiene curiosidad.

Un saludo.

Ayer a las 07:33 pm
Respuesta #2

geómetracat

  • Moderador Global
  • Mensajes: 3,330
  • País: es
  • Karma: +0/-0
  • Sexo: Masculino
Yo lo hice esta mañana, pero nunca se si un problema es lo suficiente interesante como para compartirlo y espero a que otro haga el post :laugh:
Yo entiendo que la idea es poner las soluciones de todos los días (o hasta donde lleguemos), aunque el problema en sí o nuestra solución no sea muy interesante.

Citar
Por lo que veo de nuevo tenemos prácticamente la misma solución, pero python es mucho más elegante (y, no se exactamente como funcionan los diccionarios, pero parecen ser muy útiles para estas cosas de formar funciones con dominio finito).
Sí, es básicamente la misma solución, que creo que es la obvia si estás en un lenguaje de programación que te permite trabajar con conjuntos. Los diccionarios de Python son muy útiles. Básicamente son tablas Hash, con lo que además el acceso por llave es bastante eficiente.

Citar
También lo resolví en Excel a petición de un amigo (aunque es un monstruo de cuidado  ::)), lo adjunto por si alguien tiene curiosidad.
Vaya, muy interesante la solución con Excel.
La ecuación más bonita de las matemáticas: \( d^2=0 \)

Ayer a las 10:43 pm
Respuesta #3

w a y s

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

esta es 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.List;

public class Day3 {
    private static final File INPUT = new File("2022_inputs/2022_day3_input.txt");
    private static final String LETTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    Day3(){

    }

    private String getRepeatedItem(String firstHalf, String secondHalf){
        for (int i = 0; i < firstHalf.length(); i++) {
            if(secondHalf.contains(firstHalf.charAt(i)+""))
                return firstHalf.charAt(i)+"";
        }
        return "";
    }

    private String getRepeatedBadge(String firstPack, String secondPack, String thirdPack){
        for (int i = 0; i < firstPack.length(); i++) {
            if(secondPack.contains(firstPack.charAt(i)+"") && thirdPack.contains(firstPack.charAt(i)+""))
                return firstPack.charAt(i) + "";
        }
        return "";
    }

    private int solvePartOne(){
        int sum = 0;
        try(BufferedReader br = new BufferedReader(new FileReader(INPUT))){
            String line = "", firsHalf = "", secondHalf = "",repeatedItem = "";
            while((line = br.readLine()) != null){
                firsHalf = line.substring(0,(line.length()/2));
                secondHalf = line.substring((line.length()/2));
                repeatedItem = getRepeatedItem(firsHalf,secondHalf);
                sum += LETTERS.indexOf(repeatedItem) + 1;
            }
        }catch (IOException e){
            System.err.println("Error parsing input");
        }
        return sum;
    }

    private int solvePartTwo(){
        int sum = 0, i = 0;
        String packs [] = new String[3];
        String line = "";
        try(BufferedReader br = new BufferedReader(new FileReader(INPUT))){
            while((line = br.readLine()) != null){
                if(i == 3){
                    i = 0;
                    sum += LETTERS.indexOf(getRepeatedBadge(packs[0],packs[1],packs[2])) + 1;
                    packs[i] = line;
                    i++;
                }else{
                    packs[i] = line;
                    i++;
                }
            }
            sum += LETTERS.indexOf(getRepeatedBadge(packs[0],packs[1],packs[2])) + 1;
        }catch (IOException e){
            System.err.println("Error parsing input");
        }
        return sum;
    }

    public static void main(String[] args) {
        Day3 d3 = new Day3();
        System.out.println(d3.solvePartOne());
        System.out.println(d3.solvePartTwo());
    }
}