Skip to content

Instantly share code, notes, and snippets.

@xavdid
Last active February 12, 2022 08:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xavdid/bb3b304f614e048d138d54b2d3578cdf to your computer and use it in GitHub Desktop.
Save xavdid/bb3b304f614e048d138d54b2d3578cdf to your computer and use it in GitHub Desktop.
A first attempt at AOC 2021 Day 24
# requires Python@3.10
from dataclasses import dataclass, field
from operator import add, floordiv, mod, mul
from typing import Dict, Generator, List
@dataclass
class ALU:
instructions: List[str] = field(repr=False)
inputs: str = field(repr=False)
memory: Dict[str, int] = field(
default_factory=lambda: {"w": 0, "x": 0, "y": 0, "z": 0}
)
OPERATIONS = {"add": add, "mul": mul, "div": floordiv, "mod": mod}
def value_of(self, val: str) -> int:
if val in {"w", "x", "y", "z"}:
return self.memory[val]
return int(val)
def run(self):
inputs = self.get_inputs()
for ins in self.instructions:
match ins.split():
case ["inp", var]:
self.memory[var] = next(inputs)
case ["add" | "mul" | "div" | "mod" as op, var, val]:
self.memory[var] = self.OPERATIONS[op](
self.value_of(var), self.value_of(val)
)
case ["eql", var, val]:
self.memory[var] = (
1 if self.value_of(var) == self.value_of(val) else 0
)
case _:
raise NotImplementedError(f"unknown operation: {ins}")
def get_inputs(self) -> Generator[int, None, None]:
for i in self.inputs:
yield int(i)
@property
def input_was_valid(self) -> bool:
return self.memory["z"] == 0
class Solution(...):
def part_1(self) -> int:
i = int("9" * 14)
while True:
i -= 1
model_number = str(i)
if i % 10000 == 0:
print(i)
if "0" in model_number:
continue
alu = ALU(self.input, model_number)
alu.run()
if alu.input_was_valid:
return i
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment