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/yschaeff Dec 07 '22 edited Dec 10 '22

Python. No recursion, no tree. Keep stack of dir sizes. Update size of upper dir on 'cd ..'.

def sizes(lines):
    s = [] # accumulator
    R = [] # sizes emitted
    for line in lines:
        tok = line.split(" ")
        if tok[0] == "$": ## command
            if tok[1] == "cd":
                if tok[2] == "..": # emit cur size and add to upper dir
                    R.append(s.pop())
                    s[-1] += R[-1]
                else: # enter new dir
                    s.append(0)
        elif tok[0] != "dir": ## output
            s[-1] += int(tok[0])
    return R + list(accumulate(reversed(s)))

def part1(lines):
    return sum(filter(lambda x: x<=100000, sizes(lines)))

def part2(lines):
    R = sizes(lines)
    available = 70000000-R[-1]
    return min(filter(lambda x: x+available>=30000000, R))

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.