day02 - the introduction of intcode

This commit is contained in:
Stefan Harmuth 2021-11-26 08:35:16 +01:00
parent b50168fd3b
commit fa1cd39f9a
8 changed files with 70 additions and 0 deletions

33
day02.py Normal file
View File

@ -0,0 +1,33 @@
from aoc import AOCDay
from typing import Any
from intcode import IntCode
class Day(AOCDay):
test_solutions_p1 = [100, 2, 2, 2, 30]
test_solutions_p2 = []
def part1(self) -> Any:
memory = self.getInputAsArraySplit(',', int)
memory[1] = 12
memory[2] = 2
comp = IntCode(memory, 100)
comp.run()
return comp.memory[0]
def part2(self) -> Any:
init_memory = self.getInputAsArraySplit(",", int)
for x in range(100):
for y in range(100):
memory = init_memory.copy()
memory[1] = x
memory[2] = y
comp = IntCode(memory)
comp.run()
if comp.memory[0] == 19690720:
return 100 * x + y
return -1

1
inputs/input02 Normal file
View File

@ -0,0 +1 @@
1,0,0,3,1,1,2,3,1,3,4,3,1,5,0,3,2,1,9,19,1,10,19,23,2,9,23,27,1,6,27,31,2,31,9,35,1,5,35,39,1,10,39,43,1,10,43,47,2,13,47,51,1,10,51,55,2,55,10,59,1,9,59,63,2,6,63,67,1,5,67,71,1,71,5,75,1,5,75,79,2,79,13,83,1,83,5,87,2,6,87,91,1,5,91,95,1,95,9,99,1,99,6,103,1,103,13,107,1,107,5,111,2,111,13,115,1,115,6,119,1,6,119,123,2,123,13,127,1,10,127,131,1,131,2,135,1,135,5,0,99,2,14,0,0

1
inputs/test_input02_1_0 Normal file
View File

@ -0,0 +1 @@
1,9,10,3,2,3,11,0,99,30,40,50

1
inputs/test_input02_1_1 Normal file
View File

@ -0,0 +1 @@
1,0,0,0,99

1
inputs/test_input02_1_2 Normal file
View File

@ -0,0 +1 @@
2,3,0,3,99

1
inputs/test_input02_1_3 Normal file
View File

@ -0,0 +1 @@
2,4,4,5,99,0

1
inputs/test_input02_1_4 Normal file
View File

@ -0,0 +1 @@
1,1,1,4,99,5,6,0,99

31
intcode.py Normal file
View File

@ -0,0 +1,31 @@
from typing import List
class IntCode:
def __init__(self, memory: List[int], mem_size: int = 0):
self.instr_ptr = 0
self.halted = False
self.memory = memory
if len(self.memory) < mem_size:
self.memory.extend([0] * (mem_size - len(self.memory)))
def run(self):
while not self.halted:
instr = self.memory[self.instr_ptr]
if instr == 1:
address1 = self.memory[self.instr_ptr + 1]
address2 = self.memory[self.instr_ptr + 2]
address3 = self.memory[self.instr_ptr + 3]
self.memory[address3] = self.memory[address1] + self.memory[address2]
self.instr_ptr += 4
elif instr == 2:
address1 = self.memory[self.instr_ptr + 1]
address2 = self.memory[self.instr_ptr + 2]
address3 = self.memory[self.instr_ptr + 3]
self.memory[address3] = self.memory[address1] * self.memory[address2]
self.instr_ptr += 4
elif instr == 99:
self.halted = True
else:
raise ValueError("Invalid instruction encountered at pos %d: %d" % (self.instr_ptr, instr))