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

It's not fast... but it's a solution.

+59
+59
2023/day05.py
··· 1 + import fileinput 2 + import itertools 3 + 4 + 5 + def seed_to_location(mappings, seed): 6 + curr = seed 7 + for mapping in mappings: 8 + for dest, src, rng in mapping: 9 + if src <= curr <= src + rng: 10 + curr += (dest - src) 11 + break 12 + 13 + return curr 14 + 15 + def location_to_seed(mappings, location): 16 + curr = location 17 + for mapping in reversed(mappings): 18 + for dest, src, rng in mapping: 19 + if dest <= curr < dest + rng: 20 + curr -= (dest - src) 21 + break 22 + 23 + return curr 24 + 25 + 26 + def seed_in_start_range(cand, seed_starts, seed_ranges): 27 + for start, rng in zip(seed_starts, seed_ranges): 28 + if start <= cand < start + rng: 29 + return True 30 + 31 + return False 32 + 33 + 34 + # Parse problem input. 35 + file = ''.join(fileinput.input())[:-1] 36 + seeds, *raw_mappings = file.split('\n\n') 37 + seeds = [int(x) for x in seeds.split()[1:]] 38 + 39 + mappings = [] 40 + for m in raw_mappings: 41 + nums = m.split('\n')[1:] 42 + mapping = [[int(x) for x in line.split()] for line in nums] 43 + mappings.append(mapping) 44 + 45 + 46 + # Solve Part 1. 47 + print("Part 1:", min(seed_to_location(mappings, seed) for seed in seeds)) 48 + 49 + # Solve Part 2. 50 + seed_starts = seeds[::2] 51 + seed_ranges = seeds[1::2] 52 + 53 + for location in itertools.count(start=1): 54 + seed = location_to_seed(mappings, location) 55 + if seed_in_start_range(seed, seed_starts, seed_ranges): 56 + break 57 + 58 + print("Part 2:", location) 59 +