1202 Program Alarm (Advent of Code Day 2)

Dec 5, 2019 by Chris Luedtke

Description

Process a list of integers in chunks. The first integer of each chunk will be 1, 2 or 99. If 1, the next two integers refer to the list position of two other integers that should be added. If the first integer 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?

For example:

  1. Given input:
     [1,9,10,3,2,3,11,0,99,30,40,50]
    
  2. Add 30 and 40 and assign to position 3:
     [1,9,10,70,2,3,11,0,99,30,40,50]
    
  3. Multiply 70 and 50 and assign to position 0:
     [3500,9,10,70,2,3,11,0,99,30,40,50]
    
  4. 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)