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/PaymentConscious1107 Dec 07 '22

Python

s, r = [], []
for line in open('temp.txt').read().splitlines():
    match line.strip('$').split():
        case ['cd', '..']: r.append(s.pop()); s[-1] += r[-1]
        case ['cd',f]: s.append(0)
        case [n,f] if n != 'dir': s[-1] += int(n)
sizes = list(accumulate(s[::-1])) + r
available = 70000000-max(sizes)
print("Solution 1:", sum(filter(lambda x: x<=100000, sizes)))
print("Solution 2:", min(filter(lambda x: x+available>30000000, sizes)))

1

u/daggerdragon Dec 08 '22

Inlined code is intended for short snippets of code only. Your code "block" right now is unreadable on old.reddit and many mobile clients; it's all on one line and gets cut off at the edge of the screen because it is not horizontally scrollable.

Please edit your post to use the four-spaces Markdown syntax for a code block so your code is easier to read inside a scrollable box.

1

u/[deleted] Dec 07 '22

omg, this is very compact. I can hardly understand the cases :)

1

u/jso__ Dec 07 '22

Can you give a rundown of what your code does? I understand the match statements but what do the s and r arrays hold? It seems like s is the size of the current directory, but I'm not sure about r.

Also what's the list(accumulate(s[::-1])) + r?

1

u/Waf9000 Dec 07 '22

s holds the sizes so far of each directory in the path to the current directory: if we've just finished processing /a/e from the example input and are doing the $ cd .., then

s = [size('/'), size('/a'), size('/a/e')]

where size represents the size computed so far in the process. Note that s does not keep track of the sizes of directories already processed; once a directory is completed and will never be visited again, it's moved to r. For example, if we've made it to 5626152 d.ext in the example input, we would have

s = [size('/'), size('/d')]    = [23447523, 12093194]
r = [size('/a/e'), size('/a')] = [584, 94853] # a and e are done

list(accumulate(s[::-1])) + r is just a cleanup step: at the end of the input, we have to finish moving any directories in the current path (usually including the root directory) to r. See the docs for more info on exactly what accumulate does.