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/22

+89
+89
2024/day22.py
··· 1 + import fileinput 2 + import itertools 3 + import functools 4 + import multiprocessing 5 + 6 + 7 + def mix(n, secret): 8 + return n ^ secret 9 + 10 + def prune(secret): 11 + return secret % 16777216 12 + 13 + @functools.lru_cache(None) 14 + def advance(n): 15 + a = n * 64 16 + n = mix(n, a) 17 + n = prune(n) 18 + 19 + a = int(n / 32) 20 + n = mix(n, a) 21 + n = prune(n) 22 + 23 + a = n * 2048 24 + n = mix(n, a) 25 + n = prune(n) 26 + 27 + return n 28 + 29 + 30 + def possible_windows(): 31 + for a, b, c, d in itertools.product(list(range(-9, 10)), repeat=4): 32 + yield (a, b, c, d) 33 + 34 + 35 + def gen_windows(n): 36 + """Returns the 2000th secret number and all sliding delta windows.""" 37 + windows = {} 38 + deltas = [] 39 + last = n 40 + for i in range(2000 - 1): 41 + n = advance(n) 42 + delta = (n % 10) - (last % 10) 43 + deltas.append(delta) 44 + last = n 45 + 46 + if len(deltas) >= 4: 47 + w = tuple(deltas[-4:]) 48 + if w not in windows: 49 + windows[w] = n % 10 50 + 51 + return advance(n), windows 52 + 53 + 54 + def bananas_for_window(window): 55 + bananas = 0 56 + for b in BUYERS: 57 + bananas += ALL_WINDOWS[b].get(window, 0) 58 + 59 + return bananas 60 + 61 + 62 + # Read problem input and solve part 1. 63 + part_1 = 0 64 + BUYERS = [] 65 + ALL_WINDOWS = {} 66 + 67 + for line in fileinput.input(): 68 + buyer = int(line) 69 + BUYERS.append(buyer) 70 + secret_2000, windows = gen_windows(buyer) 71 + part_1 += secret_2000 72 + ALL_WINDOWS[buyer] = windows 73 + 74 + # Solve part 2. 75 + MULTITHREAD = True 76 + NUM_THREADS = multiprocessing.cpu_count() 77 + 78 + if MULTITHREAD: 79 + with multiprocessing.Pool(processes=NUM_THREADS) as pool: 80 + results = pool.map(bananas_for_window, possible_windows()) 81 + 82 + else: 83 + results = [] 84 + for window in possible_windows(): 85 + bananas = bananas_for_window(window) 86 + results.append(bananas) 87 + 88 + print("Part 1:", part_1) 89 + print("Part 2:", max(results))