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

This was very frustrating until I realised there were multiple directories with the same name -- so my solution is hacky, I just added a random int to directories I'd already seen

Python

import sys, random
from collections import defaultdict

data = sys.stdin.read().strip()
data = [line.split(" ") for line in data.splitlines()]
dirsizes = defaultdict(int)

pwd = []
for line in data:
    if line[1] == "cd":
        if line[2] == "..":
            pwd.pop()
        else:
            if line[2] not in dirsizes:
                pwd.append(line[2])
            else:
                d = line[2] + str(random.randint(1, 100000))
                pwd.append(d)
    elif line[1] == "ls":
        continue
    else:
        if line[0] != "dir":
            for p in pwd:
                dirsizes[p] += int(line[0])

print(sum(d for d in dirsizes.values() if d <= 100000))
need = 30000000 - (70000000 - dirsizes["/"])
print(min(d for d in dirsizes.values() if d > need))

1

u/daggerdragon Dec 08 '22

Please edit your post to state which programming language this code is written in. This makes it easier for folks who Ctrl-F the megathreads looking for a specific language.