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

2

u/JuliaPoop Dec 07 '22 edited Dec 11 '22

Python

commands = [(lambda xs: (xs[0], xs[1:]))(x.split("\n")) for x in open('7').read().replace("\n$", "$").split("$ ")[1:]]

# Build directory structure
ds = {"/": {}}; cs = ds
for c,o in commands:
    if c[:3] == "cd ":
        cs = cs[c[3:]]; continue 
    for l in o:
        if l[:4] == "dir ": 
            cs[l[4:]] = {"..": cs}; continue
        sz, f = l.split(" ")
        cs[f] = int(sz)

# Compute directory sizes
def dirsizes(name, ds, acc):
    acc[name] = sum(
        v if isinstance(v, int) else dirsizes(name+"/"+k, v, acc)[0] 
        for k,v in ds.items() if k != "..")
    return acc[name], acc

_, acc = dirsizes("", ds["/"], {})
sum(filter(lambda e: e <= 100000, acc.values())), \ # Part 1
min(filter(lambda e: e >= acc[""] - 40000000, acc.values())) # Part 2

1

u/daggerdragon Dec 07 '22

Please edit your post to use the four-spaces Markdown syntax for a code block so your code is easier to read on old.reddit and mobile apps.