You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
83 lines
2.8 KiB
83 lines
2.8 KiB
#!/usr/bin/env python3
|
|
|
|
import sys, re
|
|
|
|
|
|
def key_dest(key, mp):
|
|
for src, (length,dest) in mp.items():
|
|
if key in range(src, src+length):
|
|
return dest+(key-src)
|
|
return key
|
|
|
|
|
|
def rang_dest(rang, mp):
|
|
sols = []
|
|
for (key_s, key_l) in rang:
|
|
for src, (length,dest) in dict(sorted(mp.items())).items():
|
|
if key_s in range(src,src+length):
|
|
if key_s + key_l -1 in range(src,src+length):
|
|
sols += [(dest-src+key_s,key_l)]
|
|
key_l = 0
|
|
break
|
|
else:
|
|
sols += [(dest-src+key_s, src+length-key_s)]
|
|
key_l -= (length + src - key_s)
|
|
key_s = src+length
|
|
if key_l > 0:
|
|
sols += [(key_s, key_l)]
|
|
return list(set(sols))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
lines = [line.strip('\n') for line in open(sys.argv[1])]
|
|
seeds = [int(n) for n in re.findall(r'(\d+)',lines[0])]
|
|
maps = {
|
|
'seed-to-soil': {},
|
|
'soil-to-fertilizer': {},
|
|
'fertilizer-to-water': {},
|
|
'water-to-light': {},
|
|
'light-to-temperature': {},
|
|
'temperature-to-humidity': {},
|
|
'humidity-to-location': {}}
|
|
|
|
key = ''
|
|
for line in lines[2:]:
|
|
if re.match(r'(.*) map:', line):
|
|
key = re.search(r'(?P<name>.*) map:', line).group('name')
|
|
elif re.match(r'\d+', line):
|
|
dest, src, length = [int(i) for i in re.findall(r'\d+',line)]
|
|
maps[key][src] = (length,dest)
|
|
res1 = 10000000000000000
|
|
for seed in seeds:
|
|
soil = key_dest(seed, maps['seed-to-soil'])
|
|
fert = key_dest(soil, maps['soil-to-fertilizer'])
|
|
water = key_dest(fert, maps['fertilizer-to-water'])
|
|
light = key_dest(water, maps['water-to-light'])
|
|
temp = key_dest(light, maps['light-to-temperature'])
|
|
hum = key_dest(temp, maps['temperature-to-humidity'])
|
|
loc = key_dest(hum, maps['humidity-to-location'])
|
|
if loc < res1: res1 = loc
|
|
|
|
res2 = 10000000000000000
|
|
for i in range(int(len(seeds)/2)):
|
|
src, length = seeds[i*2], seeds[i*2+1]
|
|
seed = [(src,length)]
|
|
soil = rang_dest(seed, maps['seed-to-soil'])
|
|
fert = rang_dest(soil, maps['soil-to-fertilizer'])
|
|
water = rang_dest(fert, maps['fertilizer-to-water'])
|
|
light = rang_dest(water, maps['water-to-light'])
|
|
temp = rang_dest(light, maps['light-to-temperature'])
|
|
hum = rang_dest(temp, maps['temperature-to-humidity'])
|
|
loc = rang_dest(hum, maps['humidity-to-location'])
|
|
for i,_ in loc:
|
|
if i < res2: res2 = i
|
|
|
|
|
|
# challenge 1
|
|
res1 = str(res1)
|
|
print(f"challenge 1:\n{res1}\n")
|
|
|
|
# challenge 2
|
|
res2 = str(res2)
|
|
print(f"challenge 2:\n{res2}\n")
|
|
|
|
|