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

+52
+52
2024/day05.py
··· 1 + import fileinput 2 + from collections import defaultdict 3 + 4 + from utils import parse_nums 5 + 6 + 7 + def is_unordered(graph, update): 8 + """Returns -1 if ordered, else the index of the first bad page.""" 9 + for i, n in enumerate(update): 10 + if any(n in graph[m] for m in update[i+1:]): 11 + return i 12 + 13 + return -1 14 + 15 + def mid(lst): 16 + return lst[(len(lst) - 1) // 2] 17 + 18 + 19 + on_updates = False 20 + graph = defaultdict(set) 21 + updates = [] 22 + for line in fileinput.input(): 23 + if on_updates: 24 + updates.append(parse_nums(line)) 25 + else: 26 + if line.strip(): 27 + x, y = parse_nums(line) 28 + graph[x].add(y) 29 + else: 30 + on_updates = True 31 + 32 + part_1 = 0 33 + part_2 = 0 34 + 35 + for update in updates: 36 + if is_unordered(graph, update) == -1: 37 + part_1 += mid(update) 38 + else: 39 + while True: 40 + swap = False 41 + for i, n in enumerate(update): 42 + afters = update[i+1:] 43 + if any(n in graph[a] for a in afters): 44 + update[i], update[i + 1] = update[i + 1], update[i] 45 + swap = True 46 + if not swap: 47 + break 48 + 49 + part_2 += mid(update) 50 + 51 + print("Part 1:", part_1) 52 + print("Part 2:", part_2)