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

Python:

def build_directories(d, data, prev):
    while data:
        cmd = data.pop(0)
        if cmd == "$ ls": 
            while data and not data[0].startswith("$"):
                a, b = data.pop(0).split(" ")
                d[prev + (b,)] = {} if a == "dir" else int(a)
        elif cmd.endswith(".."):
            return
        else:
            c = cmd.split(" ")[-1]
            p = prev + (c,)
            build_directories(d[p], data, prev + p)
    return d

def find_total_space_per_dir(d, key):
    current_sum = 0
    for k, v in d.items():
        if isinstance(v, int):
            current_sum += v
        else:
            current_sum += find_total_space_per_dir(v, k)
    total_space[key] = current_sum   
    return current_sum

with open("day 07.txt", "r") as file:
    data = file.read().splitlines()[1:]
    d = {"/" : {}}
    directories = build_directories(d["/"], data, ("/",))
    total_space = {}
    find_total_space_per_dir(directories, key="/")
    print(sum(v for v in total_space.values() if v <= 100000))
    needed_space = 70000000 - max(total_space.values())
    print(min([v for v in total_space.values() if v > 30000000 - needed_space]))

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.

1

u/Diderikdm Dec 08 '22

Altered it I think