Skip to content

17

https://adventofcode.com/2024/day/17

Prob1

python
import sys

reg_a = 0
reg_b = 0
reg_c = 0

def combo_operand(v: int):
    if v >= 0 and v <= 3:
        return v
    if v == 4:
        return reg_a
    elif v == 5:
        return reg_b
    elif v == 6:
        return reg_c
    raise RuntimeError('operand 7')

op_list = []

for line in sys.stdin:
    line = line.strip()
    if not line:
        continue

    if line.startswith('Register'):
        v = int(line[len('Register A: '):])
        if line.startswith('Register A:'):
            reg_a = v
        elif line.startswith('Register B:'):
            reg_b = v
        else:
            reg_c = v
    else:
        op_list = list(map(int, line.removeprefix('Program: ').split(',')))

output = []
ptr = 0
while ptr < len(op_list):
    opcode = op_list[ptr]
    operand = op_list[ptr + 1]
    if opcode == 0:
        reg_a >>= combo_operand(operand)
        ptr += 2
    elif opcode == 1:
        reg_b ^= operand
        ptr += 2
    elif opcode == 2:
        reg_b = combo_operand(operand) % 8
        ptr += 2
    elif opcode == 3:
        if reg_a == 0:
            ptr += 2
            continue
        ptr = operand
    elif opcode == 4:
        reg_b ^= reg_c
        ptr += 2
    elif opcode == 5:
        output.append(combo_operand(operand) % 8)
        ptr += 2
    elif opcode == 6:
        reg_b = reg_a >> combo_operand(operand)
        ptr += 2
    elif opcode == 7:
        reg_c = reg_a >> combo_operand(operand)
        ptr += 2
    else:
        raise RuntimeError('opcode = %d' % opcode)

print(','.join(map(str, output)))

Prob2

go
package main

import (
	"log"
)

func run2(a int64) []int {
	output := []int{}

	for a > 0 {
		b := (a % 8) ^ 5
		c := a >> b
		b ^= c
		a >>= 3
		b ^= 6
		output = append(output, int(b%8))
	}

	return output
}

func main() {
	opList := []int{2, 4, 1, 5, 7, 5, 4, 5, 0, 3, 1, 6, 5, 5, 3, 0}
	ansList := []int64{0}
	for ptr := len(opList) - 1; ptr >= 0; ptr-- {
		newAnsList := []int64{}
		for _, ans := range ansList {
			for i := range 8 {
				newAns := ans*8 + int64(i)
				res := run2(newAns)
				if len(res) > 0 && res[0] == opList[ptr] {
					newAnsList = append(newAnsList, newAns)
				}
			}
		}
		ansList = newAnsList
		log.Println(ansList)
	}

	ans := ansList[0]
	for _, aa := range ansList {
		ans = min(aa, ans)
	}
	log.Println(ans)
}

Changelog

Just observe 👀