summaryrefslogtreecommitdiff
path: root/2024/aoc2024-d17.py
blob: c5a41b156bd0f7b9d7f51f6e3a26fe1d46c47b2e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#advent of code 2024
#day 17
#code needs input reading, hardcoded my input out of convenience
#the fucking commas where part of a solution lol, misread the problem there
#if I were to reverse the logic for 3rd argument in broot function 
#it could work for longer inputs
import re
RegsRaw, ProgRaw = open("17.in","r").read().split("\n\n");
#by Eric's request, the input is removed
MyCode = [];
MyA = ; 

Register = {};
Register[0] = 0; #A
Register[1] = 0; #B
Register[2] = 0; #C

def combo(op):
	if op <= 3: return op;
	elif op == 4: return Register[0];
	elif op == 5: return Register[1];
	elif op == 6: return Register[2];

def runprogram(code,A):
	Results = [];
	InstrPointer = 0;
	Register[0] = A; #A
	while InstrPointer < len(code):
		operand = code[InstrPointer+1];
		Inst = code[InstrPointer];
		#print(InstrPointer, Inst , operand);
		if Inst == 0: Register[0] = Register[0]>>combo(operand);
		elif Inst == 1: Register[1] = Register[1]^operand;
		elif Inst == 2:	Register[1] = combo(operand)%8;
		elif Inst == 3:
			if Register[0] != 0: InstrPointer = operand -2;
		elif Inst == 4:	Register[1] = Register[1]^Register[2];
		elif Inst == 5:	Results.append(combo(operand)%8);
		elif Inst == 6:	Register[1] = Register[0]>>combo(operand);
		elif Inst == 7:	Register[2] = Register[0]>>combo(operand);
		InstrPointer += 2;
	return Results;

def broot(code,PotentialA,ind):
	valid = [];
	if ind == 0:
		PotentialA = [0];
	for pa in PotentialA:
		for option in range(8):
			A_to_check = pow(8,(15-ind))*option + pa;
			output = runprogram(code,A_to_check);
			if output[-ind-1:] == code[-ind-1:]: valid.append(A_to_check);
	if ind != 15:
		valid = broot(code,valid.copy(),ind+1);
	return valid;

part1 = ",".join([str(n) for n in runprogram(MyCode,MyA)]);
print("part 1 =", part1);

MinimalValues = broot(MyCode,[],0);
part2 = MinimalValues[0];
for mv in MinimalValues:
	if runprogram(MyCode,mv) == MyCode: part2 = min(part2,mv);

print("part 2 =",part2);