Day 7 - Advent of Code 2022

Working solutions for the day 7 puzzles.

Part One

""" day_07_01.py """

# usage: python3 day_07_01.py < input

import sys


dirs = {}
path = []
for line in sys.stdin:
    if line.startswith('$'):
        if line.startswith('$ cd '):
            _, _, directory = line.split()
            if directory == '..':
                path.pop()
            else:
                path.append(directory)
    else:
        cwd = '-'.join(path)
        files = dirs.get(cwd, [])
        atom = line.split()
        if atom[0] == 'dir':
            atom[1] = cwd + '-' + atom[1]
        files.append(atom)
        dirs[cwd] = files


def size(folder, structure):
    """ calculate size of folder and files in structure """
    total = 0
    for i, j in structure[folder]:
        if i == 'dir':
            total += size(j, structure)
        else:
            total += int(i)
    return total


candidates = []
for d in dirs:
    files = size(d, dirs)
    if files <= 100000:
        candidates.append(files)
print(sum(candidates))

Part Two

""" day_07_02.py """

# usage: python3 day_07_02.py < input

import sys


dirs = {}
path = []
for line in sys.stdin:
    if line.startswith('$'):
        if line.startswith('$ cd '):
            _, _, directory = line.split()
            if directory == '..':
                path.pop()
            else:
                path.append(directory)
    else:
        cwd = '-'.join(path)
        files = dirs.get(cwd, [])
        atom = line.split()
        if atom[0] == 'dir':
            atom[1] = cwd + '-' + atom[1]
        files.append(atom)
        dirs[cwd] = files


def size(folder, structure):
    """ calculate size of folder and files in structure """
    total = 0
    for i, j in structure[folder]:
        if i == 'dir':
            total += size(j, structure)
        else:
            total += int(i)
    return total


disk = 70000000
needed = 30000000
free = disk - size('/', dirs)

candidates = []
for d in dirs:
    files = size(d, dirs)
    if files + free >= needed:
        candidates.append(files)
print(min(candidates))