Guest User

AoC y2023 d5

a guest
Nov 12th, 2024
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.49 KB | None | 0 0
  1. from collections.abc import Sequence
  2.  
  3.  
  4. def get_seeds(line: str, as_ranges: bool) -> list[tuple[int, int]]:
  5.     seeds = line.removeprefix("seeds:").split()
  6.  
  7.     if as_ranges:
  8.         return [
  9.             (s := int(start), s + int(length))
  10.             for start, length in zip(seeds[::2], seeds[1::2])
  11.         ]
  12.     else:
  13.         return [(s := int(x), s + 1) for x in seeds]
  14.  
  15.  
  16. def impl(data: Sequence[str], as_ranges: bool) -> int:
  17.     it = iter(data)
  18.  
  19.     src_list = get_seeds(next(it), as_ranges)
  20.     dst_list = []
  21.  
  22.     for line in it:
  23.         if not line:
  24.             src_list += dst_list
  25.             dst_list = []
  26.             next(it)  # Skip "XXX-to-YYY map:" line
  27.             continue
  28.  
  29.         dst, src, len_ = map(int, line.split())
  30.  
  31.         new_src_list = []
  32.  
  33.         while src_list:
  34.             start, end = src_list.pop()
  35.  
  36.             lo = max(start, src)
  37.             hi = min(end, src + len_)
  38.  
  39.             if lo >= hi:
  40.                 new_src_list.append((start, end))
  41.                 continue
  42.  
  43.             offset = dst - src
  44.             dst_list.append((lo + offset, hi + offset))
  45.  
  46.             if lo > start:
  47.                 new_src_list.append((start, lo))
  48.  
  49.             if hi < end:
  50.                 new_src_list.append((hi, end))
  51.  
  52.         src_list = new_src_list
  53.  
  54.     return min(s for s, _ in src_list + dst_list)
  55.  
  56.  
  57. def part1(data: Sequence[str]) -> int:
  58.     return impl(data, False)
  59.  
  60.  
  61. def part2(data: Sequence[str]) -> int:
  62.     return impl(data, True)
Advertisement
Add Comment
Please, Sign In to add comment