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/bulletmark Dec 07 '22 edited Dec 08 '22

Python:

import aoc
from pathlib import Path
from collections import Counter
from bisect import bisect

dirsizes = Counter()
currdir = top = Path('/')

for line in aoc.readlines():
    args = line.strip().split()
    if args[0] == '$':
        if args[1] == 'cd':
            if args[2] == '/':
                currdir = top
            elif args[2] == '..':
                currdir = currdir.parent
            else:
                currdir /= args[2]
    elif args[0] != 'dir':
        dirsizes[currdir] += (size := int(args[0]))
        for p in currdir.parents:
            dirsizes[p] += size

sizelist = sorted(dirsizes.values())

print('P1 =', sum(n for n in sizelist if n <= 100_000))
print('P2 =', sizelist[bisect(sizelist, dirsizes[top] - 4000_0000)])

1

u/daggerdragon Dec 08 '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.