From 146c08362712a4800cdf5755e3c87891589cb917 Mon Sep 17 00:00:00 2001 From: Nick Krichevsky Date: Mon, 2 Dec 2019 00:28:30 -0500 Subject: [PATCH] Add solution to day2 part 2, refactoring part 1 --- day2/main.py | 40 ++++++++++++++++++++++++++++++++-------- 1 file changed, 32 insertions(+), 8 deletions(-) diff --git a/day2/main.py b/day2/main.py index 104412d..25b7241 100644 --- a/day2/main.py +++ b/day2/main.py @@ -1,17 +1,18 @@ import itertools -def part1(inputs): - inputs[1] = 12 - inputs[2] = 2 +def execute_program(inputs): + TERMINATE_OPCODE = 99 + ADD_OPCODE = 1 + MULTIPLY_OPCODE = 2 + for i, opcode in itertools.islice(enumerate(inputs), 0, None, 4): operation = None - # Terminate opcode - if opcode == 99: + if opcode == TERMINATE_OPCODE: break - elif opcode == 1: + elif opcode == ADD_OPCODE: operation = lambda a, b: a + b - elif opcode == 2: + elif opcode == MULTIPLY_OPCODE: operation = lambda a, b: a * b else: raise Exception('Bad opcode: ' + str(opcode)) @@ -24,8 +25,31 @@ def part1(inputs): return inputs[0] +def part1(inputs): + inputs[1] = 12 + inputs[2] = 2 + + return execute_program(inputs) + + +def part2(inputs): + DESIRED_OUTPUT = 19690720 + + for i in range(100): + for j in range(100): + inputs[1] = i + inputs[2] = j + # Execute the program, making sure we clone the inputs array so we don't reuse the list + result = execute_program(inputs[:]) + if result == DESIRED_OUTPUT: + return 100 * i + j + else: + raise Exception('Could not find result') + + if __name__ == '__main__': with open('input.txt') as f: inputs = [int(item) for item in f.read().rstrip().split(',')] - print(part1(inputs)) + print(part1(inputs[:])) + print(part2(inputs[:]))