-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday24.py
More file actions
97 lines (84 loc) · 2.88 KB
/
Copy pathday24.py
File metadata and controls
97 lines (84 loc) · 2.88 KB
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
from rich.console import Console
from typing import List, Tuple, Optional, Dict
def read_program(lines: List[str]) -> List[List[str]]:
program = []
for line in lines:
program.append(line.strip().split())
return program
def read_val(registers: Dict[str, int], num_or_register: str) -> int:
if (num := registers.get(num_or_register)) is not None:
return num
return int(num_or_register)
def write_val(registers: Dict[str, int], register: str, num: int):
registers[register] = num
def validate_solution(
program: List[List[str]],
registers: Dict[str, int],
input: str,
) -> Optional[str]:
inputs = list(input)
pc = 0
while pc < len(program):
if pc == len(program):
if read_val(registers, "z") == 0:
return f"{input}"
else:
return None
instr = program[pc][0]
if instr == "inp":
dest = program[pc][1]
input_val = inputs.pop(0)
write_val(registers, dest, int(input_val))
else:
op1 = program[pc][1]
op2 = program[pc][2]
if instr == "add":
write_val(
registers,
op1,
read_val(registers, op1) + read_val(registers, op2),
)
elif instr == "mul":
write_val(
registers,
op1,
read_val(registers, op1) * read_val(registers, op2),
)
elif instr == "div":
write_val(
registers,
op1,
read_val(registers, op1) // read_val(registers, op2),
)
elif instr == "mod":
write_val(
registers,
op1,
read_val(registers, op1) % read_val(registers, op2),
)
elif instr == "eql":
write_val(
registers,
op1,
1 if read_val(registers, op1) == read_val(registers, op2) else 0,
)
pc += 1
return registers["z"] == 0
console = Console()
with open("day24.txt", "r") as file:
program = read_program(file.readlines())
console.print("[b yellow]Day 24[/b yellow]")
registers = {"x": 0, "y": 0, "w": 0, "z": 0}
result = validate_solution(program, registers, "99999795919456")
console.print(result)
result = validate_solution(program, registers, "45311191516111")
console.print(result)
# did this by hand to find those solutions, then the program is just a way to verify that it succeeds
# input has to abide by these constraints:
# input[4] = input[3]
# input[5] = input[2] - 2
# input[8] = input[7] + 4
# input[9] = input[6] - 8
# input[11] = input[10] - 5
# input[12] = input[1] - 4
# input[13] = input[0] - 3