logan_2023/day5/d5p1.py

115 lines
2.5 KiB
Python

#!/usr/bin/python3
from enum import IntEnum
import re
import sys
class Maps(IntEnum):
seeds = 0
seedToSoil = 1
soilToFertilizer = 2
fertilizerToWater = 3
waterToLight = 4
lightToTemp = 5
temptoHumidity = 6
humidityToLocation = 7
class Column(IntEnum):
DESTINATION = 0
ORIGIN = 1
LENGTH = 2
def file_load(path):
file = FileAccess.open(path, FileAccess.READ)
content = file.get_as_text()
return content
def strarr_to_arr(data):
new = []
for i in range(0, len(data)):
new.append(data[i])
return new
def input_clean(data):
output = []
for i in range(len(data)):
regex = re.compile(r"^(.*-to-.* map:\n)|^(seeds: )")
output.append(regex.sub("", data[i]))
return output
# bad variable names :(
def input_format(data):
new = []
for i in range(0, len(data)):
temp = strarr_to_arr(data[i].split("\n"))
temp4 = []
for j in range(0, len(temp)):
temp2 = strarr_to_arr(temp[j].split(" "))
temp3 = []
for k in range(0, len(temp2)):
if not len(temp2[k]):
continue
temp3.append(int(temp2[k]))
temp4.append(temp3)
new.append(temp4)
return new
def is_mapped(thing, data):
for v in thing:
if data >= v[Column.ORIGIN] and data <= v[Column.ORIGIN]+v[Column.LENGTH]:
return v[Column.DESTINATION] + (data-v[Column.ORIGIN])
return data
def is_revmapped(thing, data):
for v in thing:
if data >= v[Column.DESTINATION] and data <= v[Column.DESTINATION]+v[Column.LENGTH]:
return v[Column.ORIGIN] + (data-v[Column.DESTINATION])
return data
def map_input(data, seed):
temp = seed
for map in range(Maps.seedToSoil, Maps.humidityToLocation+1):
temp = is_mapped(data[map], temp)
#print("Output: %s %s" % [map, temp])
return temp
def revmap_input(data, location):
temp = location
for map in range(Maps.humidityToLocation, Maps.seedToSoil-1, -1):
temp = is_revmapped(data[map], temp)
#print("Output: %s %s" % [map, temp])
return temp
def __main__():
print("Hello!")
temp = ""
with open(sys.argv[1]) as f:
temp = f.read().split("\n\n")
temp = input_clean(temp)
data = input_format(temp)
seeds = data[0][0]
print(seeds)
minval = 2**32
for seed in seeds:
location = map_input(data, seed)
if location < minval:
minval = location
print("Answer: %s" % minval)
__main__()