Add solution to day2 part 2, refactoring part 1
This commit is contained in:
parent
b5d2571284
commit
146c083627
40
day2/main.py
40
day2/main.py
|
@ -1,17 +1,18 @@
|
||||||
import itertools
|
import itertools
|
||||||
|
|
||||||
|
|
||||||
def part1(inputs):
|
def execute_program(inputs):
|
||||||
inputs[1] = 12
|
TERMINATE_OPCODE = 99
|
||||||
inputs[2] = 2
|
ADD_OPCODE = 1
|
||||||
|
MULTIPLY_OPCODE = 2
|
||||||
|
|
||||||
for i, opcode in itertools.islice(enumerate(inputs), 0, None, 4):
|
for i, opcode in itertools.islice(enumerate(inputs), 0, None, 4):
|
||||||
operation = None
|
operation = None
|
||||||
# Terminate opcode
|
if opcode == TERMINATE_OPCODE:
|
||||||
if opcode == 99:
|
|
||||||
break
|
break
|
||||||
elif opcode == 1:
|
elif opcode == ADD_OPCODE:
|
||||||
operation = lambda a, b: a + b
|
operation = lambda a, b: a + b
|
||||||
elif opcode == 2:
|
elif opcode == MULTIPLY_OPCODE:
|
||||||
operation = lambda a, b: a * b
|
operation = lambda a, b: a * b
|
||||||
else:
|
else:
|
||||||
raise Exception('Bad opcode: ' + str(opcode))
|
raise Exception('Bad opcode: ' + str(opcode))
|
||||||
|
@ -24,8 +25,31 @@ def part1(inputs):
|
||||||
return inputs[0]
|
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__':
|
if __name__ == '__main__':
|
||||||
with open('input.txt') as f:
|
with open('input.txt') as f:
|
||||||
inputs = [int(item) for item in f.read().rstrip().split(',')]
|
inputs = [int(item) for item in f.read().rstrip().split(',')]
|
||||||
|
|
||||||
print(part1(inputs))
|
print(part1(inputs[:]))
|
||||||
|
print(part2(inputs[:]))
|
||||||
|
|
Loading…
Reference in a new issue