diff --git a/day05/sol2.py b/day05/sol2.py index fbae921..05931df 100644 --- a/day05/sol2.py +++ b/day05/sol2.py @@ -9,32 +9,31 @@ def read_map(input): def overlap(a,b, x,y): - """ if two ranges a..a+b and x..x+y overlap, returns the overlapping range""" + """ if two ranges a..b and x..y overlap, returns the overlapping range""" if b <= x or y <= a: return (0,0) # no overlap return max(a,x), min(b,y) def lookup(map, m,n): - r = [] - used = [] + r = [] # (start,count) + used = [] # (start,end) for dst, src, count in map: a,b = overlap(m,m+n, src,src+count) if a != b: assert a < b used.append((a,b)) r.append((a-src+dst,b-a)) - if not used: - r.append((m,n)) - else: - used.sort() - end = m+n - for a,b in used: - assert m <= a - if m < a: - r.append((m, a-m)) - m = b - if m < end: - r.append((m,end-m)) + # unused values translate to themselves + used.sort() + end = m+n + for a,b in used: + assert m <= a + if m < a: + r.append((m, a-m)) + m = b + if m < end: + r.append((m,end-m)) + #r.sort() return r def nums(s): @@ -60,17 +59,22 @@ def read_puzzle(input): print(seeds) print(maps) - locs = [] + return seeds,maps + +def solve(data): + seeds, maps = data + for i in range(0, len(seeds), 2): m,n = seeds[i:i+2] - print(n, lookup(maps[('seed','soil')], m,n), seed2loc(maps, m,n)) - locs.extend(seed2loc(maps, m,n)) + print(n, lookup(maps[('seed','soil')], m,n)) + + ranges = [(seeds[i],seeds[i+1]) for i in range(0,len(seeds),2)] + locs = seed2loc(maps, ranges) print(min(locs)) -def seed2loc(maps, m,n): - r = [(m,n)] +def seed2loc(maps, r): for a,b in [ ('seed', 'soil'), ('soil', 'fertilizer'), @@ -89,4 +93,5 @@ def seed2loc(maps, m,n): return r import sys -read_puzzle(sys.stdin) +p = read_puzzle(sys.stdin) +solve(p)