Description
Process a list of integers in chunks of 4. The first integer of each chunk will be 1
, 2
or 99
. If the first integer of the chunk is 1
, the next two integers refer to the list position of two other integers that should be added. If the first integer of the chunk is 2
, the same applies, but multiplication should be used. The fourth integer refers to the position in the list where the result should be placed. If the first integer is 99
, the process is complete and should terminate.
What is the final value of the list element at position 0?
You’ll need to get your own input for this challenge from this Advent of Code problem.
Example:
- Given input:
[1,9,10,3,2,3,11,0,99,30,40,50]
- Add 30 and 40 and assign to position 3:
[1,9,10,70,2,3,11,0,99,30,40,50]
- Multiply 70 and 50 and assign to position 0:
[3500,9,10,70,2,3,11,0,99,30,40,50]
- Hit 99 and terminate
Solution
# Part 1
ls = open('input.txt').read().strip()
ls = [int(i) for i in ls.split(',')]
def solve(ls, noun=12, verb=2):
ls[1] = noun
ls[2] = verb
i = 0
while i < len(ls) - 4 and ls[i] != 99:
assert ls[i] in {1, 2, 99}
a = ls[ls[i + 1]]
b = ls[ls[i + 2]]
if ls[i] == 1:
ls[ls[i + 3]] = a + b
elif ls[i] == 2:
ls[ls[i + 3]] = a * b
i += 4
return ls[0]
print(solve(ls.copy()))
# Part 2
for noun in range(100):
for verb in range(100):
if solve(ls.copy(), noun, verb) == 19690720:
print(noun, verb, 100 * noun + verb)