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

Python 3

Using pathlib was made it much more readable.

from pathlib import Path
from collections import defaultdict

def parse_tokens(tokens:list[str], cwd:Path, files:list[Path]) -> Path:
    if tokens[0]=="$":
        if tokens[1]=="cd":
            cwd = (cwd / tokens[2]).resolve()
    elif tokens[0]!="dir":
        key = str(cwd / tokens[1]).strip("C:")
        files[key] = int(tokens[0])
    return cwd

with open("2022/input07.txt") as file:
    data = [line.strip().split() for line in file]

cwd = Path("")
files = {}

for tokens in data:
    cwd = parse_tokens(tokens, cwd, files)

dir_sizes = defaultdict(int)
total_size = 0
for path, size in files.items():
    while (path:=path.rsplit("\\",1)[0]):
        dir_sizes[path]+=size
    total_size+=size

result1 = sum(s for s in dir_sizes.values() if s<100000)
print("answer 1:", result1)

size_to_remove = total_size - 40_000_000
result2 = min(s for s in dir_sizes.values() if s>size_to_remove)
print("answer 2:", result2)

1

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

Edit: thanks for fixing it! <3

1

u/SvenViktorJonsson Dec 08 '22

Thank you, I thought 1 back tick would do the job. But apparently not.

1

u/daggerdragon Dec 08 '22

FYI: Single backticks are intended for short snippets of inlined code, not an entire block of code.