StyleInCode

RSS

 

Day 9 - Advent of Code 2024

9 December 2024

Working solutions for the day 9 puzzles.

Part One

""" day_09_01.py """

# usage: python3 day_09_01.py < input

import sys


def gaps(filesystem):
    """ gaps in filesystem """
    i = filesystem.index('.')
    for block in filesystem[i + 1:]:
        if block != '.':
            return True
    return False


def swap(filesystem):
    """ last block to first gap """
    i = filesystem.index('.')
    for j in range(len(filesystem) - 1, -1, -1):
        block = filesystem[j]
        if block != '.':
            return (filesystem[:i] + [block]
                    + filesystem[i + 1:j] + ['.']
                    + filesystem[j + 1:])
    return filesystem


def main():
    """ let's go """
    blocks = []
    with sys.stdin as infile:
        i = 0
        data = infile.read(2)
        while data != '':
            blocks.extend(int(data[0]) * [f'{i}'])
            if len(data.strip()) == 2:
                blocks.extend(int(data[1]) * ['.'])
            i += 1
            data = infile.read(2)

    while gaps(blocks):
        blocks = swap(blocks)

    print(sum(i * int(data) for i, data in enumerate(blocks) if data != '.'))


if __name__ == '__main__':
    main()

Part Two

""" day_09_02.py """

# usage: python3 day_09_02.py < input

import sys


def swap(task, filesystem):
    """ swap task with first gap large enough """
    size = filesystem.count(task)
    for i, _ in enumerate(filesystem):
        if filesystem[i:i + size] == size * ['.']:
            j = filesystem.index(task)
            if j < i:
                break
            return (filesystem[:i] + size * [task]
                    + filesystem[i + size:j] + size * ['.']
                    + filesystem[j + size:])
    return filesystem


def main():
    """ let's go """
    blocks = []
    with sys.stdin as infile:
        i = 0
        data = infile.read(2)
        while data != '':
            blocks.extend(int(data[0]) * [f'{i}'])
            if len(data.strip()) == 2:
                blocks.extend(int(data[1]) * ['.'])
            i += 1
            data = infile.read(2)

    job = blocks[-1]
    while job != '0':
        blocks = swap(job, blocks)
        job = f'{int(job) - 1}'

    print(sum(i * int(data) for i, data in enumerate(blocks) if data != '.'))


if __name__ == '__main__':
    main()

Categories

Links