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.

Update day23.py

+15 -23
+15 -23
2016/day23.py
··· 16 16 # Toggling instructions modifes the program, so operate on a copy instead. 17 17 program = deepcopy(program) 18 18 19 - while True: 20 - if pc >= len(program): 21 - return regs 22 - 19 + while pc < len(program): 23 20 cmd, x, y = program[pc] 24 21 25 22 if cmd == 'cpy': 26 - # The following instructions simply perform multiplication: 23 + # The following set of instructions performs multiplication: 27 24 # cpy b c 28 25 # inc a 29 26 # dec c 30 27 # jnz c -2 31 28 # dec d 32 29 # jnz d -5 30 + # 33 31 # Perform a peephole optimization by doing the following: 34 32 # - Set a to b*d 35 33 # - Set c and d to 0. 36 - # - Advance the PC by 5 instructions. 34 + # - Advance the PC by 6 to jump past the instructions. 37 35 next_cmds, next_regs = zip(*program[pc+1:pc+5])[0:2] 38 36 39 37 if x.isalpha() and next_cmds == ('inc', 'dec', 'jnz', 'dec'): ··· 42 40 regs[a] = regs[x] * regs[d] 43 41 regs[c] = 0 44 42 regs[d] = 0 45 - pc += 5 43 + pc += 6 46 44 continue 47 45 48 - # Ignore copy instructions that try to copy a value into an 46 + # Ignore cpy instructions that try to copy a value into an 49 47 # immediate value (occurs when toggling instructions). 50 48 if y.isalpha(): 51 49 regs[y] = reg_or_val(regs, x) ··· 64 62 continue 65 63 66 64 elif cmd == 'tgl': 67 - x = reg_or_val(regs, x) 68 - to_toggle = pc + x 65 + i = pc + reg_or_val(regs, x) 69 66 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' 67 + ncmd, nx, ny = program[i] 68 + except IndexError: 69 + pass 80 70 else: 81 - if cng == 'jnz': 82 - program[to_toggle][0] = 'cpy' 71 + if ny == 'null': 72 + program[i][0] = 'dec' if ncmd == 'inc' else 'inc' 83 73 else: 84 - program[to_toggle][0] = 'jnz' 74 + program[i][0] = 'cpy' if ncmd == 'jnz' else 'jnz' 85 75 86 76 pc += 1 77 + 78 + return regs 87 79 88 80 89 81 PROGRAM = []