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 2024/17

+87
+87
2024/day17.py
··· 1 + import fileinput 2 + from utils import parse_nums 3 + 4 + 5 + def simulate(program, a, b, c): 6 + pc = 0 7 + out = [] 8 + 9 + while pc < len(program): 10 + opcode, literal = program[pc:pc+2] 11 + 12 + if literal <= 3: 13 + combo = literal 14 + elif literal == 4: 15 + combo = a 16 + elif literal == 5: 17 + combo = b 18 + elif literal == 6: 19 + combo = c 20 + 21 + if opcode == 0: 22 + a = a // (2 ** combo) 23 + elif opcode == 1: 24 + b ^= literal 25 + elif opcode == 2: 26 + b = combo % 8 27 + elif opcode == 3: 28 + if a != 0: 29 + pc = literal * 2 30 + continue 31 + elif opcode == 4: 32 + b ^= c 33 + elif opcode == 5: 34 + out.append(combo % 8) 35 + elif opcode == 6: 36 + b = a // (2 ** combo) 37 + elif opcode == 7: 38 + c = a // (2 ** combo) 39 + 40 + pc += 2 41 + 42 + return out 43 + 44 + 45 + # Read problem input. 46 + for i, line in enumerate(fileinput.input()): 47 + if i == 0: 48 + A = parse_nums(line)[0] 49 + elif i == 1: 50 + B = parse_nums(line)[0] 51 + elif i == 2: 52 + C = parse_nums(line)[0] 53 + elif i == 4: 54 + PROGRAM = parse_nums(line) 55 + 56 + 57 + # Simulate the program for part 1. 58 + part_1 = simulate(PROGRAM, A, B, C) 59 + print("Part 1:", ','.join(str(n) for n in part_1)) 60 + 61 + 62 + # Solve part 2. 63 + # 64 + # For the problem input, note that each "output byte" is affected 65 + # by a byte in order of the starting A register. You can manually 66 + # dial in some of the high bytes of the starting value to narrow 67 + # the search space until it's something viable to be simulated. 68 + start = 0o5322350130000000 69 + for s in range(start, start + 10000000): 70 + out = [] 71 + A = s 72 + B = 0 73 + C = 0 74 + while True: 75 + B = A % 8 76 + B ^= 2 77 + C = (A // (2**B)) 78 + A >>= 3 79 + B ^= C 80 + B ^= 7 81 + out.append(B % 8) 82 + if A == 0: 83 + break 84 + 85 + if out == PROGRAM: 86 + print("Part 2:", s) 87 + break