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

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

06 Diciembre, 2022, 09:00 am
Leído 535 veces

Eparoh

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

Los enunciados del día 6 (Tuning Trouble) son los siguientes:

Parte 1:
Spoiler
The preparations are finally complete; you and the Elves leave camp on foot and begin to make your way toward the star fruit grove.

As you move through the dense undergrowth, one of the Elves gives you a handheld device. He says that it has many fancy features, but the most important one to set up right now is the communication system.

However, because he's heard you have significant experience dealing with signal-based systems, he convinced the other Elves that it would be okay to give you their one malfunctioning device - surely you'll have no problem fixing it.

As if inspired by comedic timing, the device emits a few colorful sparks.

To be able to communicate with the Elves, the device needs to lock on to their signal. The signal is a series of seemingly-random characters that the device receives one at a time.

To fix the communication system, you need to add a subroutine to the device that detects a start-of-packet marker in the datastream. In the protocol being used by the Elves, the start of a packet is indicated by a sequence of four characters that are all different.

The device will send your subroutine a datastream buffer (your puzzle input); your subroutine needs to identify the first position where the four most recently received characters were all different. Specifically, it needs to report the number of characters from the beginning of the buffer to the end of the first such four-character marker.

For example, suppose you receive the following datastream buffer:

mjqjpqmgbljsphdztnvjfqwrcgsmlb

After the first three characters (mjq) have been received, there haven't been enough characters received yet to find the marker. The first time a marker could occur is after the fourth character is received, making the most recent four characters mjqj. Because j is repeated, this isn't a marker.

The first time a marker appears is after the seventh character arrives. Once it does, the last four characters received are jpqm, which are all different. In this case, your subroutine should report the value 7, because the first start-of-packet marker is complete after 7 characters have been processed.

Here are a few more examples:

    bvwbjplbgvbhsrlpgdmjqwftvncz: first marker after character 5
    nppdvjthqldpwncqszvftbrmjlhg: first marker after character 6
    nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg: first marker after character 10
    zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw: first marker after character 11

How many characters need to be processed before the first start-of-packet marker is detected?
[cerrar]
Parte 2:
Spoiler
Your device's communication system is correctly detecting packets, but still isn't working. It looks like it also needs to look for messages.

A start-of-message marker is just like a start-of-packet marker, except it consists of 14 distinct characters rather than 4.

Here are the first positions of start-of-message markers for all of the above examples:

    mjqjpqmgbljsphdztnvjfqwrcgsmlb: first marker after character 19
    bvwbjplbgvbhsrlpgdmjqwftvncz: first marker after character 23
    nppdvjthqldpwncqszvftbrmjlhg: first marker after character 23
    nznrnfrfntjfmvfwmzdfjlvtqnbhcprsg: first marker after character 29
    zcfzfwzzqfrljwzlrfnpqdbhtmscgvjw: first marker after character 26

How many characters need to be processed before the first start-of-message marker is detected?
[cerrar]

Muy sencillito el de hoy utilizando otra vez conjuntos. Dejo por aquí mis soluciones en Maple y Excel:

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

Primer:=proc(F,n)
   local N, i;
      N:=length(F);
      for i from 1 to N-(n-1) do
         if nops(convert(F[i..i+(n-1)],set))=n then
            RETURN(i+(n-1));
         fi;
      od;
end:

Primer(F,4);
Primer(F,14);

Un saludo.

06 Diciembre, 2022, 12:12 pm
Respuesta #1

geómetracat

  • Moderador Global
  • Mensajes: 4,065
  • País: es
  • Karma: +0/-0
  • Sexo: Masculino
Hoy me ha parecido muy fácil, usando conjuntos.

Un par de one-liners en Python:
Código: [Seleccionar]
with open("input6.txt") as f:
    inp = f.read().splitlines()[0]

# Part 1
print([i for i in range(4, len(inp)) if len(set(inp[i-4:i]))==4][0])

# Part 2
print([i for i in range(14, len(inp)) if len(set(inp[i-14:i]))==14][0])

Añadido:
Solo por diversión, un one-liner (un poco largo, eso sí) que saca los valores de ambas partes, incluyendo la lectura del fichero de texto:
Código: [Seleccionar]
print(list(map((lambda inp: lambda n: [i for i in range(n, len(inp)) if len(set(inp[i-n:i]))==n][0])(open("input6.txt").read().splitlines()[0]), [4,14])))
La ecuación más bonita de las matemáticas: \( d^2=0 \)

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

Eparoh

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

Hoy me ha parecido muy fácil, usando conjuntos.

Sí, con conjuntos era inmediato hoy.

Solo por diversión, un one-liner (un poco largo, eso sí) que saca los valores de ambas partes, incluyendo la lectura del fichero de texto:
Código: [Seleccionar]
print(list(map((lambda inp: lambda n: [i for i in range(n, len(inp)) if len(set(inp[i-n:i]))==n][0])(open("input6.txt").read().splitlines()[0]), [4,14])))

Muy chulo. Auque no soy especialmente fan de los one-line, la verdad es dudo que se pueda hacer con menos  :laugh:

Un saludo.

06 Diciembre, 2022, 07:34 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,

hoy me ha tocado resolver 2  ;D, mi solución en java:

Código: [Seleccionar]
package aoc_2022;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

public class Day6 {
    private static final File INPUT = new File("2022_inputs/2022_day6_input.txt");

    Day6(){
    }
   
    private int solve(){
        String solution = "";
        int c, i = 0;
        try(FileReader reader = new FileReader(INPUT)){
            while(solution.length()!=4){ //swap 4 for 14 to get part's two solution
                c = reader.read();
                if(solution.contains((char)c + "")){
                    solution = solution.substring(solution.indexOf((char)c)+1);
                    solution += (char)c;
                }else
                    solution+=(char)c;
                i++;
            }
        }catch (IOException e){
            System.err.println("Error parsing file.");
        }
        return i;
    }


    public static void main(String[] args) {
        Day6 d6 = new Day6();
        System.out.println(d6.solve());
    }
}