Advertisement
icarussiano

day 5 python

Dec 5th, 2023 (edited)
787
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.56 KB | None | 0 0
  1. import re
  2. with open("input") as file:
  3.     data=file.read().splitlines()
  4. loc = []
  5. keys = ['seeds','seed','soil','fert','wate','ligh','temp','humi']
  6. maps = dict(zip(keys, [[] for _ in range(len(keys))]))
  7. def mappa(c, v):
  8.     for x,y,z in maps[c]:
  9.         if v>=y and v < y+z:
  10.             return x + v - y
  11.     return v
  12.  
  13. #riempio dizionario
  14. for i,line in enumerate(data):
  15.     if i==0:
  16.         maps['seeds']=list(map(int, line.split(":")[1].split()))
  17.         continue
  18.     if re.search(r"\w+:",line):
  19.         r=line[0:4]
  20.     if re.search(r"\d+", line):
  21.         x, y, z = map(int, line.split())
  22.         maps[r].append((x, y, z))
  23.  
  24. #faccio mappaggi
  25. for s in maps['seeds']:
  26.     s = int(s)
  27.     for x in maps:
  28.         if x=='seeds':
  29.             continue
  30.         s = mappa(x, s)
  31.     loc.append(s)
  32.  
  33. print(f"Part1:{min(loc)}")
  34.  
  35. loc=[]
  36. def mappa_range(c, ranges):
  37.     p = []
  38.     for (x, y, z) in maps[c]:
  39.         e = y + z
  40.         new_range = []
  41.         while ranges:
  42.             (a, b) = ranges.pop()
  43.             if min(b, y) > a:
  44.                 new_range.append((a, min(b, y)))
  45.             if min(e,b)>max(y,a):
  46.                 p.append((max(y,a) - y + x, min(e,b) - y + x))
  47.             if b > max(e, a):
  48.                 new_range.append((max(e, a), b))
  49.         ranges = new_range
  50.     return p + ranges
  51.  
  52. for i,j in zip(maps['seeds'][::2],maps['seeds'][1::2]):
  53.     ranges = [(i, i + j)]
  54.     for x in maps:
  55.         if x=='seeds':
  56.             continue
  57.         ranges = mappa_range(x, ranges)
  58.     loc.append(min(ranges)[0])
  59.  
  60. print(f"Part2:{min(loc)}")
  61.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement