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

+65
+65
2025/day05.py
··· 1 + import fileinput 2 + 3 + 4 + def is_fresh(ingredient, intervals): 5 + for a, b in intervals: 6 + if a <= ingredient <= b: 7 + return True 8 + 9 + return False 10 + 11 + 12 + def is_overlap(a, b, c, d): 13 + """Returns the (min, max) if (a, b) and (c, d) overlap, else None.""" 14 + if a <= c <= d <= b: 15 + return a, b 16 + elif c <= a <= b <= d: 17 + return c, d 18 + elif c <= b <= d and a <= c <= b: 19 + return a, d 20 + 21 + return None, None 22 + 23 + 24 + def merge_intervals(intervals): 25 + def _merge_one_pass(intervals): 26 + new_intervals = [] 27 + 28 + for y in range(len(intervals)): 29 + for x in range(len(intervals)): 30 + if x == y: 31 + continue 32 + 33 + a, b = intervals[x] 34 + c, d = intervals[y] 35 + m, n = is_overlap(a, b, c, d) 36 + 37 + if m is not None and n is not None: 38 + new_intervals = [interval for i, interval in enumerate(intervals) if i != x and i != y] 39 + new_intervals.append((m, n)) 40 + return new_intervals 41 + 42 + return intervals 43 + 44 + while True: 45 + new_intervals = _merge_one_pass(intervals) 46 + if len(new_intervals) == len(intervals): 47 + return intervals 48 + intervals = new_intervals 49 + 50 + 51 + # Read problem input. 52 + INTERVALS = [] 53 + INGREDIENTS = [] 54 + for line in fileinput.input(): 55 + line = line.strip() 56 + if '-' in line: 57 + a, b = line.split('-') 58 + INTERVALS.append((int(a), int(b))) 59 + elif line: 60 + INGREDIENTS.append(int(line)) 61 + 62 + # Solve problem. 63 + INTERVALS = merge_intervals(INTERVALS) 64 + print("Part 1:", sum(is_fresh(ingredient, INTERVALS) for ingredient in INGREDIENTS)) 65 + print("Part 2:", sum(b - a + 1 for a, b in INTERVALS))