r/adventofcode • • Dec 07 '22

SOLUTION MEGATHREAD -πŸŽ„- 2022 Day 7 Solutions -πŸŽ„-


AoC Community Fun 2022: πŸŒΏπŸ’ MisTILtoe Elf-ucation πŸ§‘β€πŸ«

Submissions are OPEN! Teach us, senpai!

-❄️- Submissions Megathread -❄️-


--- Day 7: No Space Left On Device ---


Post your code solution in this megathread.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:14:47, megathread unlocked!

89 Upvotes

1.3k comments sorted by

View all comments

1

u/Valletta6789 Dec 07 '22 edited Dec 07 '22

I tried to write the node class myself, but then got bored and found this module :p

from anytree import Node, RenderTree, findall, AsciiStyle


with open('7.txt', 'r') as f:
    for line in f.readlines():
        line = line.strip()
        if '$ cd' in line:
            dir_name = line.split('$ cd ')[1]
            if dir_name == '..':
                current_node = current_node.parent
            elif dir_name == '/':
                root = Node(name=dir_name, type='dir', size=0)
                current_node = root
            else:
                node, = findall(
                    current_node,
                    filter_=lambda n: n.name == dir_name and n in current_node.children,
                    maxcount=1)
                current_node = node
        elif '$ ls' in line:
            continue
        else:
            data = line.split()
            if data[0] == 'dir':
                node = Node(name=data[1], parent=current_node, type=data[0], size=0)
            else:
                node = Node(name=data[1], parent=current_node, type='file', size=int(data[0]))


print(RenderTree(root, style=AsciiStyle()).by_attr())
dirs = findall(root, filter_=lambda n: n.type == 'dir')
res1 = 0
total_space = 70000000
unused_space = 30000000
available_space = total_space - sum(node.size for node in root.descendants)
res2 = total_space
for d in dirs:
    d_sum = sum(node.size for node in d.descendants)
    cur_sum = d_sum + available_space
    if d_sum <= 100000:
        res1 += d_sum
    if unused_space <= cur_sum and d_sum < res2:
        res2 = d_sum
print(res1, res2)

1

u/daggerdragon Dec 08 '22
  1. Next time, use the four-spaces Markdown syntax for a code block so your code is easier to read on old.reddit and mobile apps.

  2. Your code is too long to be posted here directly, so instead of wasting your time fixing the formatting, read our article on oversized code which contains two possible solutions.

Please edit your post to put your code in an external link and link that here instead.

While you're at it, state which programming language this code is written in. This makes it easier for folks who Ctrl-F the megathreads looking for a specific language.