mirror of
https://github.com/thib8956/advent-of-code.git
synced 2026-11-27 00:46:34 +00:00
intcode: cleanup
This commit is contained in:
1 parent
06956da329
commit
a9d4619cac
3 files changed
+41
-25
No files matched your search
@@ -1 +1,4 @@
|
|||||||
from .intcode import Interpreter, Mode, Operation, interpret_intcode
|
from .intcode import Interpreter as Interpreter
|
||||||
|
from .intcode import Mode as Mode
|
||||||
|
from .intcode import Operation as Operation
|
||||||
|
from .intcode import interpret_intcode as interpret_intcode
|
||||||
@@ -12,22 +12,22 @@ def get_nth_digit(n, number):
|
|||||||
|
|
||||||
|
|
||||||
class Operation(Enum):
|
class Operation(Enum):
|
||||||
ADDITION = 1
|
ADDITION = 1 # Add the first two arguments and stores the result in the third argument.
|
||||||
MULTIPLICATION = 2
|
MULTIPLICATION = 2 # Like 1, but for multiplication
|
||||||
INPUT = 3
|
INPUT = 3 # Take a single integer as input, store it in the first argument
|
||||||
OUTPUT = 4
|
OUTPUT = 4 # Output the first argument
|
||||||
JMP_IF_TRUE = 5
|
JMP_IF_TRUE = 5 # If arg1 is non-zero, set the instruction pointer to arg2
|
||||||
JMP_IF_FALSE = 6
|
JMP_IF_FALSE = 6 # If arg1 is zero, set the instruction pointer to arg2
|
||||||
LESS_THAN = 7
|
LESS_THAN = 7 # If arg1 is less than arg2, store 1 in arg3, otherwise store 0
|
||||||
EQUALS = 8
|
EQUALS = 8 # Like 7, but for equality
|
||||||
BASE = 9
|
BASE = 9 # Adjusts the relative base by arg1
|
||||||
TERMINATION = 99
|
TERMINATION = 99 # Halts the program
|
||||||
|
|
||||||
|
|
||||||
class Mode(Enum):
|
class Mode(Enum):
|
||||||
POSITION = 0
|
POSITION = 0 # The parameter is the address of a cell to be read or written.
|
||||||
IMMEDIATE = 1
|
IMMEDIATE = 1 # The parameter is the value read. (This mode is never used for writing.)
|
||||||
RELATIVE = 2
|
RELATIVE = 2 # The parameter is added to the relative base register to obtain the address of the cell to be read or written.
|
||||||
|
|
||||||
|
|
||||||
class Instruction:
|
class Instruction:
|
||||||
@@ -127,16 +127,24 @@ class Instruction:
|
|||||||
def handle_unknown(self):
|
def handle_unknown(self):
|
||||||
raise ValueError(f"Unknown operation <{self.operation}> @ [{self.ip}]")
|
raise ValueError(f"Unknown operation <{self.operation}> @ [{self.ip}]")
|
||||||
|
|
||||||
|
def _read_memory(self, address):
|
||||||
|
# Negative addresses are invalid
|
||||||
|
if address < 0: raise ValueError(f"Negative address {address}")
|
||||||
|
# Addresses beyond the memory size must be treated as 0, memort is like an infinite tape
|
||||||
|
if address >= len(self.memory): return 0
|
||||||
|
return self.memory[address]
|
||||||
|
|
||||||
def _get_value(self, offset):
|
def _get_value(self, offset):
|
||||||
value = self.memory[self.ip + offset]
|
value = self._read_memory(self.ip + offset)
|
||||||
match self.modes[offset - 1]:
|
match self.modes[offset - 1]:
|
||||||
case Mode.POSITION: return self.memory[value] if value < len(self.memory) else 0
|
case Mode.POSITION: address = value
|
||||||
case Mode.IMMEDIATE: return value
|
case Mode.IMMEDIATE: return value
|
||||||
case Mode.RELATIVE: return self.memory[value + self.base]
|
case Mode.RELATIVE: address = value + self.base
|
||||||
case _: raise ValueError(f"{self.modes[offset - 1]}")
|
case _: raise ValueError(f"Invalid mode: {self.modes[offset - 1]}")
|
||||||
|
return self._read_memory(address)
|
||||||
|
|
||||||
def _get_write_addr(self, offset):
|
def _get_write_addr(self, offset):
|
||||||
value = self.memory[self.ip + offset]
|
value = self._read_memory(self.ip + offset)
|
||||||
match self.modes[offset - 1]:
|
match self.modes[offset - 1]:
|
||||||
case Mode.POSITION: return value
|
case Mode.POSITION: return value
|
||||||
case Mode.RELATIVE: return value + self.base
|
case Mode.RELATIVE: return value + self.base
|
||||||
@@ -155,9 +163,9 @@ class Instruction:
|
|||||||
|
|
||||||
class Interpreter:
|
class Interpreter:
|
||||||
logger = logging.getLogger("Interpreter")
|
logger = logging.getLogger("Interpreter")
|
||||||
def __init__(self, program, stdin=[]):
|
def __init__(self, program, stdin=None):
|
||||||
self.ip = 0
|
self.ip = 0
|
||||||
self.stdin = stdin
|
self.stdin = stdin or []
|
||||||
self.stdout = []
|
self.stdout = []
|
||||||
self.memory = program[::]
|
self.memory = program[::]
|
||||||
self.halted = False
|
self.halted = False
|
||||||
@@ -172,8 +180,9 @@ class Interpreter:
|
|||||||
instruction = Instruction(self.memory, self.ip, self.base)
|
instruction = Instruction(self.memory, self.ip, self.base)
|
||||||
# pause if INP + break on input
|
# pause if INP + break on input
|
||||||
if instruction.operation == Operation.INPUT:
|
if instruction.operation == Operation.INPUT:
|
||||||
if break_on_input and self.stdin == []:
|
if self.stdin == []:
|
||||||
break
|
if break_on_input: break
|
||||||
|
else: raise RuntimeError("No input available")
|
||||||
else:
|
else:
|
||||||
instruction.input = self.stdin.pop(0)
|
instruction.input = self.stdin.pop(0)
|
||||||
# execute instruction
|
# execute instruction
|
||||||
@@ -188,7 +197,7 @@ class Interpreter:
|
|||||||
self.halted = True
|
self.halted = True
|
||||||
|
|
||||||
|
|
||||||
def interpret_intcode(program, stdin=[]):
|
def interpret_intcode(program, stdin=None):
|
||||||
interpreter = Interpreter(program, stdin)
|
interpreter = Interpreter(program, stdin)
|
||||||
interpreter.interpret(break_on_output=False)
|
interpreter.interpret(break_on_output=False)
|
||||||
return interpreter
|
return interpreter
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
from intcode import *
|
from intcode import *
|
||||||
|
|
||||||
|
|
||||||
def run_test(program, expected_mem=None, stdin=[], expected_out=None):
|
def run_test(program, expected_mem=None, stdin=None, expected_out=None):
|
||||||
mem = program[::]
|
mem = program[::]
|
||||||
out = interpret_intcode(mem, stdin=stdin)
|
out = interpret_intcode(mem, stdin=stdin)
|
||||||
if expected_mem is not None:
|
if expected_mem is not None:
|
||||||
@@ -22,6 +22,10 @@ def test_day2():
|
|||||||
run_test(program, expected)
|
run_test(program, expected)
|
||||||
|
|
||||||
|
|
||||||
|
def test_input_output():
|
||||||
|
run_test([3,0,4,0,99], stdin=[42], expected_out=[42])
|
||||||
|
|
||||||
|
|
||||||
def test_day5_basic():
|
def test_day5_basic():
|
||||||
# Using position mode, consider whether the input is equal to 8; output 1
|
# Using position mode, consider whether the input is equal to 8; output 1
|
||||||
# (if it is) or 0 (if it is not).
|
# (if it is) or 0 (if it is not).
|
||||||
|
|||||||
Reference in new issue
Block a user