2019-12-02 - 1202 Program Alarm
(original .ipynb)
Day 2 puzzle input is a list of integers which represent opcodes which comprise a small program (mine is here). Part 1 involves writing an interpreter for these opcodes and finding the result. Part 2 involves finding values you can swap into the second and third positions of the code result in the largest output value.
opcode_add = 1 opcode_mul = 2 opcode_terminate = 99 def op_add(x, y): return x + y def op_mul(x, y): return x * y def decode_op(op): if op == opcode_add: return op_add elif op == opcode_mul: return op_mul else: raise Exception(f"Invalid opcode {op}") def run_intcode(program): pc = 0 opcode = program[pc] while opcode != opcode_terminate: arg0 = program[pc + 1] arg1 = program[pc + 2] dest = program[pc + 3] op = decode_op(opcode) program[dest] = op(program[arg0], program[arg1]) pc += 4 opcode = program[pc] return program[0] assert 2 == run_intcode([1,0,0,0,99]) assert 2 == run_intcode([2,3,0,3,99]) assert 2 == run_intcode([2,4,4,5,99,0]) assert 30 == run_intcode([1,1,1,4,99,5,6,0,99])
puzzle_input_lines = open("puzzle_input/day2.txt", "r").read().split(",") puzzle_input = [int(line) for line in puzzle_input_lines] def run_program(noun, verb, program): program_copy = [ x for x in program ] program_copy[1] = noun program_copy[2] = verb return run_intcode(program_copy) print(run_program(12, 2, puzzle_input))
3101844
def brute_force_noun_verb(): for noun in range(0, 100): for verb in range(0, 100): answer = run_program(noun, verb, puzzle_input) if answer == 19690720: return (100 * noun) + verb raise Exception("No appropriate noun/verb pair found") print(brute_force_noun_verb())
8478
# test that [99] just returns 99 for sake of curiosity. [1],[2,1] etc will probably raise argument out of range exception print(run_intcode([99]))
99