My Advent of Code solutions in Python. kevinyap.ca/2019/12/going-fast-in-advent-of-code/
advent-of-code python
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

at main 77 lines 1.9 kB view raw
1import fileinput 2 3# Read input 4TAPE = [int(x) for x in fileinput.input()[0].split(',')] 5TAPE += [None, None, None, None] 6 7 8def handle_mode(tape, mode_op, a, b, c): 9 op = mode_op % 100 10 mode_a = (mode_op // 100) % 10 11 mode_b = (mode_op // 1000) % 10 12 mode_c = (mode_op // 10000) % 10 13 14 return op, mode_a, mode_b, mode_c 15 16 17def emulate(input): 18 pc = 0 19 tape = TAPE[:] 20 outs = [] 21 22 while pc < len(tape): 23 mode_op, a, b, c = tape[pc:pc+4] 24 op, mode_a, mode_b, mode_c = handle_mode(tape, mode_op, a, b, c) 25 26 # ADD a b c 27 if op == 1: 28 tape[c] = (a if mode_a else tape[a]) + (b if mode_b else tape[b]) 29 pc += 4 30 31 # MUL a b c 32 elif op == 2: 33 tape[c] = (a if mode_a else tape[a]) * (b if mode_b else tape[b]) 34 pc += 4 35 36 # INP a 37 elif op == 3: 38 tape[a] = input 39 pc += 2 40 41 # OUT b 42 elif op == 4: 43 outs.append(a if mode_a else tape[a]) 44 pc += 2 45 46 # JZ a b 47 elif op == 5: 48 if (a if mode_a else tape[a]) != 0: 49 pc = (b if mode_b else tape[b]) 50 else: 51 pc += 3 52 53 # JNZ a b 54 elif op == 6: 55 if (a if mode_a else tape[a]) == 0: 56 pc = (b if mode_b else tape[b]) 57 else: 58 pc += 3 59 60 # LT a b c 61 elif op == 7: 62 tape[c] = 1 if (a if mode_a else tape[a]) < (b if mode_b else tape[b]) else 0 63 pc += 4 64 65 # EQ a b c 66 elif op == 8: 67 tape[c] = 1 if (a if mode_a else tape[a]) == (b if mode_b else tape[b]) else 0 68 pc += 4 69 70 # HALT 71 elif op == 99: 72 if not all(x == 0 for x in outs[:-1]): 73 return "Bad output", outs 74 return outs[-1] 75 76print "Diagnostic code for system ID 1:", emulate(1) 77print "Diagnostic code for system ID 5:", emulate(5)