StyleInCode

RSS

 

Day 17 - Advent of Code 2024

17 December 2024

Working solutions for the day 17 puzzles.

Part One

""" day_17_01.py """

# usage: python3 day_17_01.py < input

import re
import sys


def combo(value, cpu_registers):
    """ evaluate combo value """
    match value:
        case 0 | 1 | 2 | 3:
            return value
        case 4:
            return cpu_registers['A']
        case 5:
            return cpu_registers['B']
        case 6:
            return cpu_registers['C']
        case _:
            raise ValueError


def xdv(value, cpu_registers):
    """ evaluate the divide function """
    return cpu_registers['A'] // 2 ** combo(value, cpu_registers)


program = []
registers = {}

with sys.stdin as infile:
    for i in ['A', 'B', 'C']:
        registers[i] = int(re.findall(r'\d+', infile.readline())[0])
    infile.readline()
    program = [int(i) for i in re.findall(r'\d+', infile.readline())]

output = []
ip = 0
while ip < len(program):
    operand = program[ip + 1]
    match program[ip]:
        case 0:  # adv
            registers['A'] = xdv(operand, registers)
        case 1:  # bxl
            registers['B'] = registers['B'] ^ operand
        case 2:  # bst
            registers['B'] = combo(operand, registers) % 8
        case 3:  # jnz
            if registers['A'] != 0:
                ip = operand - 2
        case 4:  # bxc
            registers['B'] = registers['B'] ^ registers['C']
        case 5:  # out
            output.append(str(combo(operand, registers) % 8))
        case 6:  # bdv
            registers['B'] = xdv(operand, registers)
        case 7:  # cdv
            registers['C'] = xdv(operand, registers)
        case _:
            raise ValueError

    ip += 2

print(','.join(output))

Categories

Links