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

4

u/ItIsNeverLupus Dec 07 '22

Python

Started with an implementation that used a look-up dictionary to store the size of each folder separate and recursively call all subfolder sizes in the end. But I didn't account for duplicate folder naming and I got a bit stuck with the recursive approach. Then decided to use the absolute path storing and simply update of each parent folder each time a file is found. Not really nice code, but straightforward and it works.

def main():
    with open("input.txt", mode="r", encoding="utf8") as file:
        folder_sizes = {}
        folder_path = []

        lines = file.read().splitlines()
        for line in lines:
            commands = line.split()
            if commands[0] == "$":
                if commands[1] == "cd":
                    if commands[2] == "..":
                        folder_path = folder_path[:-1]
                    elif commands[2] == "/":
                        folder_path = ["/"]
                    else:
                        folder_path.append(commands[2])
            else:
                if commands[0] != "dir":
                    current_path = ""
                    for folder in folder_path:
                        if current_path != "/" and folder != "/":
                            current_path += "/"
                        current_path += folder
                        folder_sizes[current_path] = folder_sizes.get(current_path, 0) + int(commands[0])

    # Part 1
    print(sum(value for name, value in folder_sizes.items() if value < 100000))

    # Part 2
    needed_space = 30000000 - (70000000 - folder_sizes.get("/"))
    print(min(value for name, value in folder_sizes.items() if value >= needed_space))


main()

2

u/[deleted] Dec 07 '22

Haha, I did almost the same thing. I tried a recursive approach but it hit max recursion depth on full input so I rewrote it to update the size as each file was added.

I also forgot there could be duplicate directory names and just used the name to identify them rather than the full path - that was a pain to fix and you don't notice it on the test input.

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.