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.

Add solution for 2016/23

+125
+97
2016/day23.py
··· 1 + import fileinput 2 + from copy import deepcopy 3 + 4 + 5 + def reg_or_val(regs, x): 6 + try: 7 + return int(x) 8 + except ValueError: 9 + return regs[x] 10 + 11 + 12 + def emulate(program, a=0, b=0, c=0, d=0): 13 + pc = 0 14 + regs = {'a': a, 'b': b, 'c': c, 'd': d} 15 + 16 + # Toggling instructions modifes the program, so operate on a copy instead. 17 + program = deepcopy(program) 18 + 19 + while True: 20 + if pc >= len(program): 21 + return regs 22 + 23 + cmd, x, y = program[pc] 24 + 25 + if cmd == 'cpy': 26 + # Subroutines that look like this perform multiplication: 27 + # cpy b c 28 + # inc a 29 + # dec c 30 + # jnz c -2 31 + # dec d 32 + # jnz d -5 33 + # Perform a lookahead and optimize it by doing the following: 34 + # - Set a to b*d 35 + # - Set c and d to 0. 36 + # - Move forward 5 instructions. 37 + next_cmds, next_regs = zip(*program[pc+1:pc+5])[0:2] 38 + 39 + if x.isalpha() and next_cmds == ('inc', 'dec', 'jnz', 'dec'): 40 + a, _, c, d = next_regs 41 + 42 + regs[a] = regs[x] * regs[d] 43 + regs[c] = 0 44 + regs[d] = 0 45 + pc += 5 46 + continue 47 + 48 + # Ignore copy instructions that try to copy a value into an 49 + # immediate value (occurs when toggling instructions). 50 + if y.isalpha(): 51 + regs[y] = reg_or_val(regs, x) 52 + 53 + elif cmd == 'inc': 54 + regs[x] += 1 55 + 56 + elif cmd == 'dec': 57 + regs[x] -= 1 58 + 59 + elif cmd == 'jnz': 60 + x = reg_or_val(regs, x) 61 + 62 + if x != 0: 63 + pc += reg_or_val(regs, y) 64 + continue 65 + 66 + elif cmd == 'tgl': 67 + x = reg_or_val(regs, x) 68 + to_toggle = pc + x 69 + try: 70 + cng, nx, ny = program[to_toggle] 71 + except: 72 + pc += 1 73 + continue 74 + 75 + if ny == 'null': 76 + if cng == 'inc': 77 + program[to_toggle][0] = 'dec' 78 + else: 79 + program[to_toggle][0] = 'inc' 80 + else: 81 + if cng == 'jnz': 82 + program[to_toggle][0] = 'cpy' 83 + else: 84 + program[to_toggle][0] = 'jnz' 85 + 86 + pc += 1 87 + 88 + 89 + PROGRAM = [] 90 + 91 + for line in fileinput.input(): 92 + # Add null argument to pad inc/dec instructions 93 + instruction = line + ' null' 94 + PROGRAM.append(instruction.split()[:3]) 95 + 96 + print "Value to send to safe:", emulate(PROGRAM, a=7)['a'] 97 + print "Actual value for safe:", emulate(PROGRAM, a=12)['a']
+26
2016/inputs/23.txt
··· 1 + cpy a b 2 + dec b 3 + cpy a d 4 + cpy 0 a 5 + cpy b c 6 + inc a 7 + dec c 8 + jnz c -2 9 + dec d 10 + jnz d -5 11 + dec b 12 + cpy b c 13 + cpy c d 14 + dec d 15 + inc c 16 + jnz d -2 17 + tgl c 18 + cpy -16 c 19 + jnz 1 c 20 + cpy 94 c 21 + jnz 82 d 22 + inc a 23 + inc d 24 + jnz d -2 25 + inc c 26 + jnz c -5
+2
2016/outputs/23.txt
··· 1 + 12748 2 + 479009308