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

0 Usuarios y 2 Visitantes están viendo este tema.

07 Diciembre, 2022, 08:07 pm
Leído 530 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 7 (No Space Left On Device) son los siguientes:

Parte 1:
Spoiler
You can hear birds chirping and raindrops hitting leaves as the expedition proceeds. Occasionally, you can even hear much louder sounds in the distance; how big do the animals get out here, anyway?

The device the Elves gave you has problems with more than just its communication system. You try to run a system update:

$ system-update --please --pretty-please-with-sugar-on-top
Error: No space left on device

Perhaps you can delete some files to make space for the update?

You browse around the filesystem to assess the situation and save the resulting terminal output (your puzzle input). For example:

$ cd /
$ ls
dir a
14848514 b.txt
8504156 c.dat
dir d
$ cd a
$ ls
dir e
29116 f
2557 g
62596 h.lst
$ cd e
$ ls
584 i
$ cd ..
$ cd ..
$ cd d
$ ls
4060174 j
8033020 d.log
5626152 d.ext
7214296 k

The filesystem consists of a tree of files (plain data) and directories (which can contain other directories or files). The outermost directory is called /. You can navigate around the filesystem, moving into or out of directories and listing the contents of the directory you're currently in.

Within the terminal output, lines that begin with $ are commands you executed, very much like some modern computers:

    cd means change directory. This changes which directory is the current directory, but the specific result depends on the argument:
        cd x moves in one level: it looks in the current directory for the directory named x and makes it the current directory.
        cd .. moves out one level: it finds the directory that contains the current directory, then makes that directory the current directory.
        cd / switches the current directory to the outermost directory, /.
    ls means list. It prints out all of the files and directories immediately contained by the current directory:
        123 abc means that the current directory contains a file named abc with size 123.
        dir xyz means that the current directory contains a directory named xyz.

Given the commands and output in the example above, you can determine that the filesystem looks visually like this:

- / (dir)
  - a (dir)
    - e (dir)
      - i (file, size=584)
    - f (file, size=29116)
    - g (file, size=2557)
    - h.lst (file, size=62596)
  - b.txt (file, size=14848514)
  - c.dat (file, size=8504156)
  - d (dir)
    - j (file, size=4060174)
    - d.log (file, size=8033020)
    - d.ext (file, size=5626152)
    - k (file, size=7214296)

Here, there are four directories: / (the outermost directory), a and d (which are in /), and e (which is in a). These directories also contain files of various sizes.

Since the disk is full, your first step should probably be to find directories that are good candidates for deletion. To do this, you need to determine the total size of each directory. The total size of a directory is the sum of the sizes of the files it contains, directly or indirectly. (Directories themselves do not count as having any intrinsic size.)

The total sizes of the directories above can be found as follows:

    The total size of directory e is 584 because it contains a single file i of size 584 and no other directories.
    The directory a has total size 94853 because it contains files f (size 29116), g (size 2557), and h.lst (size 62596), plus file i indirectly (a contains e which contains i).
    Directory d has total size 24933642.
    As the outermost directory, / contains every file. Its total size is 48381165, the sum of the size of every file.

To begin, find all of the directories with a total size of at most 100000, then calculate the sum of their total sizes. In the example above, these directories are a and e; the sum of their total sizes is 95437 (94853 + 584). (As in this example, this process can count files more than once!)

Find all of the directories with a total size of at most 100000. What is the sum of the total sizes of those directories?
[cerrar]
Parte 2:
Spoiler
Now, you're ready to choose a directory to delete.

The total disk space available to the filesystem is 70000000. To run the update, you need unused space of at least 30000000. You need to find a directory you can delete that will free up enough space to run the update.

In the example above, the total size of the outermost directory (and thus the total amount of used space) is 48381165; this means that the size of the unused space must currently be 21618835, which isn't quite the 30000000 required by the update. Therefore, the update still requires a directory with total size of at least 8381165 to be deleted before it can run.

To achieve this, you have the following options:

    Delete directory e, which would increase unused space by 584.
    Delete directory a, which would increase unused space by 94853.
    Delete directory d, which would increase unused space by 24933642.
    Delete directory /, which would increase unused space by 48381165.

Directories e and a are both too small; deleting them would not free up enough space. However, directories d and / are both big enough! Between these, choose the smallest: d, increasing unused space by 24933642.

Find the smallest directory that, if deleted, would free up enough space on the filesystem to run the update. What is the total size of that directory?
[cerrar]

Mi solución en Maple y Excel:

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

Suma_hasta_cota:=proc(F,cota,Lv)
   local Nivel, i, S, dato, N, T, Aborta;
      N:=nops(F);
      Nivel:=Lv;
      Aborta:=1;
      i:=2;
      S:=0;
      while Nivel >= Lv and i<N and Aborta=1 do
         i:=i+1;
         dato:=F[i][1];
         if dato <> "dir" and dato <> "$" then
            S:=S+parse(dato);
            if S>cota then
               Aborta:=0;
            fi;
         elif dato = "$" then
            if F[i][3] = ".." then
               Nivel:=Nivel-1;
            else
               Nivel:=Nivel+1;
               T:=Suma_hasta_cota(F[i..],cota,Nivel);
               S:=S+T[1];
               if S>cota then
                  Aborta:=0;
               fi;
               i:=i+T[2]-1;
               Nivel:=T[3];
            fi;
         fi;
      od;
   RETURN([S,i,Nivel,Aborta]);
end:
Suma_dir:=proc(F,cota)
   local T;
      T:=Suma_hasta_cota(F,cota,0);
   RETURN(T[1]*T[4]);
end:
Directorios:=proc(F)
   local N, L, i;
      N:=nops(F);
      L:=[];
         for i from 1 to N do
            if F[i][2] = "cd" then
               if F[i][3] <> ".." then
                  L:=[op(L),i]
               fi;
            fi;
         od;
   RETURN(L);
end:
Suma_total:=proc(F,cota)
   local S, Dir, i;
      S:=0;
      Dir:=Directorios(F);
      for i in Dir do
         S:=S+Suma_dir(F[i..],cota);
      od;
   RETURN(S);
end:
Libera_espacio:=proc(F,Total,Need)
   local Ocupado, Dir, R, R_aux, i;
      Ocupado:=Suma_dir(F,infinity);
      Dir:=Directorios(F)[2..];
      R:=Ocupado;
      for i in Dir do
         R_aux:=Suma_dir(F[i..],infinity);
         if Total-(Ocupado-R_aux)>=Need and R_aux<R then
            R:=R_aux;
         fi;
      od;
   RETURN(R);
end:

Suma_total(F,100000);
Libera_espacio(F,70000000,30000000);

¡Vamos chicos que no decaiga la cosa que ya va una semana!  :aplauso:

La verdad es que el de hoy me ha costado, no se me da nada bien la programación recursiva. Pero bueno, ha salido y se ejecuta instatáneamente en mi ordenador que tampoco es nada del otro mundo, así que soy feliz (sobre todo con la solución de Excel, que creo que si ha sido ingeniosa) :laugh:

Un saludo.

07 Diciembre, 2022, 11:53 pm
Respuesta #1

geómetracat

  • Moderador Global
  • Mensajes: 4,065
  • País: es
  • Karma: +0/-0
  • Sexo: Masculino
Ahí va la mía, un tanto in extremis. Hoy no me he podido poner hasta hace un rato y cuando he visto el enunciado (el típico problema de árboles del AoC) he estado a punto de no hacerlo. Pero al final me he animado. No estoy nada orgulloso de la solución, la verdad, creo que es una implementación bastante mala de un árbol.

Código: [Seleccionar]
with open("input7.txt") as f:
    inp = f.read().splitlines()
   
inp = [x.split() for x in inp]

class Tree:
   
    def __init__(self, name, parent, values, children, size = None):
        self.name = name
        self.parent = parent
        self.values = values
        self.children = children
        self.size = size
   
    def update_child(self, child):
        self.children.append(child)
   
    def update_values(self, value):
        self.values.append(value)
       
    def update_size(self, size):
        self.size = size
       
    def get_name(self):
        return self.name
   
    def get_parent(self):
        return self.parent
   
    def get_children(self):
        return self.children
   
    def get_values(self):
        return self.values
   
    def get_size(self):
        return self.size
   
def create_file_tree(instructions):
    file_tree = Tree(None, None, [], [])
    current = file_tree
    for inst in instructions:
        if inst[0] == '$' and inst[1] == 'cd':
            if inst[2] == "..":
                current = current.get_parent()
            else:
                new = Tree(name = inst[2], parent = current, children = [], values = [])
                current.update_child(new)
                current = new
        elif inst[0][0] in '123456789':
            current.update_values((int(inst[0]), inst[1]))
    return file_tree
       
file_tree = create_file_tree(inp)
file_tree = file_tree.get_children()[0]

# Part 1
def compute_size(file_tree):
    if not file_tree.get_children():
        file_tree.update_size(sum([x for (x, _) in file_tree.get_values()]))
    else:
        new_size = sum([x for (x, _) in file_tree.get_values()]) + sum([compute_size(x).get_size() for x in file_tree.get_children()])
        file_tree.update_size(new_size)
    return file_tree

file_tree = compute_size(file_tree)

def get_sizes(file_tree):
    if not file_tree.get_children():
        size = file_tree.get_size()
        return [size]
    return [file_tree.get_size()] + [y for x in file_tree.get_children() for y in get_sizes(x)]

print(sum([x for x in get_sizes(file_tree) if x<=100000]))

# Part 2
unused = 70000000 - file_tree.get_size()
print(min([x for x in get_sizes(file_tree) if x+unused >= 30000000]))
La ecuación más bonita de las matemáticas: \( d^2=0 \)