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

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

04 Diciembre, 2022, 11:56 am
Leído 945 veces

Eparoh

  • $$\Large \color{#c88359}\pi\,\pi\,\pi\,\pi$$
  • Mensajes: 981
  • País: es
  • Karma: +0/-0
  • Sexo: Masculino
Bueno, hoy abro yo el hilo  :P

Los enunciados del día 4 (Camp Cleanup) son:

Parte 1:
Spoiler
Space needs to be cleared before the last supplies can be unloaded from the ships, and so several Elves have been assigned the job of cleaning up sections of the camp. Every section has a unique ID number, and each Elf is assigned a range of section IDs.

However, as some of the Elves compare their section assignments with each other, they've noticed that many of the assignments overlap. To try to quickly find overlaps and reduce duplicated effort, the Elves pair up and make a big list of the section assignments for each pair (your puzzle input).

For example, consider the following list of section assignment pairs:

2-4,6-8
2-3,4-5
5-7,7-9
2-8,3-7
6-6,4-6
2-6,4-8

For the first few pairs, this list means:

    Within the first pair of Elves, the first Elf was assigned sections 2-4 (sections 2, 3, and 4), while the second Elf was assigned sections 6-8 (sections 6, 7, 8).
    The Elves in the second pair were each assigned two sections.
    The Elves in the third pair were each assigned three sections: one got sections 5, 6, and 7, while the other also got 7, plus 8 and 9.

This example list uses single-digit section IDs to make it easier to draw; your actual list might contain larger numbers. Visually, these pairs of section assignments look like this:

.234.....  2-4
.....678.  6-8

.23......  2-3
...45....  4-5

....567..  5-7
......789  7-9

.2345678.  2-8
..34567..  3-7

.....6...  6-6
...456...  4-6

.23456...  2-6
...45678.  4-8

Some of the pairs have noticed that one of their assignments fully contains the other. For example, 2-8 fully contains 3-7, and 6-6 is fully contained by 4-6. In pairs where one assignment fully contains the other, one Elf in the pair would be exclusively cleaning sections their partner will already be cleaning, so these seem like the most in need of reconsideration. In this example, there are 2 such pairs.

In how many assignment pairs does one range fully contain the other?
[cerrar]

Parte 2:
Spoiler
It seems like there is still quite a bit of duplicate work planned. Instead, the Elves would like to know the number of pairs that overlap at all.

In the above example, the first two pairs (2-4,6-8 and 2-3,4-5) don't overlap, while the remaining four pairs (5-7,7-9, 2-8,3-7, 6-6,4-6, and 2-6,4-8) do overlap:

    5-7,7-9 overlaps in a single section, 7.
    2-8,3-7 overlaps all of the sections 3 through 7.
    6-6,4-6 overlaps in a single section, 6.
    2-6,4-8 overlaps in sections 4, 5, and 6.

So, in this example, the number of overlapping assignment pairs is 4.

In how many assignment pairs do the ranges overlap?
[cerrar]

Hoy creo que era muy sencillito. Dejo mis soluciones en Maple y Excel (me he viciado a hacerlo en Excel  ::)):

Código: [Seleccionar]
F:=readdata(cat(currentdir(),"\\Template 4.txt"),[integer, integer, integer, integer]):
F:=[seq(map(abs,F[i]),i=1..nops(F))]:

Total_overlap:=proc(L)
      if (L[1]<=L[3] and L[4]<=L[2]) or (L[3]<=L[1] and L[2]<=L[4]) then
         RETURN(1);
      else
         RETURN(0);
      fi;
end:

Overlap:=proc(L)
      if L[2]<L[3] or L[4]<L[1] then
         RETURN(0);
      else
         RETURN(1);
      fi;
end:

add(x, x in map(Total_overlap,F));
add(x, x in map(Overlap,F));

Un saludo.

PD: Hice un poco de "trampas" y modifiqué ligeramente el archivo .txt que da el problema. Utilice la función reemplazar del bloc de notas para reemplazar todas las comas por espacios, pues así podía leer de golpe los datos con Maple y no tenía que hacer ningún bucle más para tratarlos.

04 Diciembre, 2022, 04:16 pm
Respuesta #1

geómetracat

  • Moderador Global
  • Mensajes: 4,065
  • País: es
  • Karma: +0/-0
  • Sexo: Masculino
Ahí va la mía en Python. De nuevo es esencialmente la misma que la tuya.
Código: [Seleccionar]
with open("input4.txt") as f:
    inp = [x.split(',') for x in f.read().splitlines()]

inp = [(list(map(int, x[0].split('-'))), list(map(int,x[1].split('-')))) for x in inp]

# Part 1
print(sum(map(lambda x: (x[0][0]<=x[1][0] and x[0][1]>=x[1][1]) or (x[1][0]<=x[0][0] and x[1][1] >= x[0][1]), inp)))

# Part 2
print(sum(map(lambda x: not(x[0][1]<x[1][0] or x[1][1]<x[0][0]), inp)))

De momento facilito... Pero ya me sé de otros años cómo va esto, empieza muy fácil hasta que de repente un día ya no es tan fácil...
La ecuación más bonita de las matemáticas: \( d^2=0 \)

04 Diciembre, 2022, 08:04 pm
Respuesta #2

Eparoh

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

De momento facilito... Pero ya me sé de otros años cómo va esto, empieza muy fácil hasta que de repente un día ya no es tan fácil...

Esperemos que al menos los difíciles caigan en fin de semana  :P

04 Diciembre, 2022, 08:54 pm
Respuesta #3

w a y s

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

os dejo por aquí 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;

class Pair{
    private int i,f;

    Pair(){
        this.i = 0;
        this.f = 0;
    }

    Pair(int i, int f){
        this.i = i;
        this.f = f;
    }

    public int getI() {
        return i;
    }

    public void setI(int i) {
        this.i = i;
    }

    public int getF() {
        return f;
    }

    public void setF(int f) {
        this.f = f;
    }

    public void setPair(int i, int f){
        this.setI(i);
        this.setF(f);
    }
}

public class Day4 {
    private static final File INPUT = new File("2022_inputs/2022_day4_input.txt");
    private int count, overlapCount;

    Day4(){
        this.count = 0;
        this.overlapCount = 0;
    }

    private boolean contains(Pair p1, Pair p2){
        return p1.getI()<=p2.getI() && p2.getF()<=p1.getF();
    }

    private boolean overlaps(Pair p1, Pair p2){
        return p1.getF()>= p2.getI() && p1.getF() <= p2.getF() ;
    }

    private void solvePartOne(){
        String line = "";
        Pair p1 = new Pair();
        Pair p2 = new Pair();
        String[] numbers;
        try(BufferedReader br = new BufferedReader(new FileReader(INPUT))){
            while((line = br.readLine()) != null){
                numbers = line.split(" ");
                p1.setPair(Integer.parseInt(numbers[0]),Integer.parseInt(numbers[1]));
                p2.setPair(Integer.parseInt(numbers[2]),Integer.parseInt(numbers[3]));
                if(contains(p1,p2) || contains(p2,p1))
                    this.count++;
                if(overlaps(p1,p2) || overlaps(p2,p1))
                    this.overlapCount++;
            }
        }catch (IOException e){
            System.err.println("Error parsing input.");
        }
    }

    public static void main(String[] args) {
        Day4 d4 = new Day4();
        d4.solvePartOne();
        System.out.println(d4.count);
        System.out.println(d4.overlapCount);
    }
}

De momento vamos al día, a ver si lo conseguimos terminar.  :laugh: