advent_of_code/2023/5/5_2.py

54 lines
1.4 KiB
Python
Raw Permalink Normal View History

#!/usr/bin/env python
# 2023 - Advent Of Code 5 - part 2
# file = 'input_example.txt'
file = 'input.txt'
# pylint: disable=consider-using-with
input_lines = [line.strip('\n') for line in open(file, encoding="utf-8")]
seeds_ranges = [int(x) for x in input_lines[0].split(':')[1].split(' ') if x != '']
print(f'seeds: {seeds_ranges}')
seeds = []
# acc = 0
# for r in range(0, len(seeds_ranges), 2):
# num = seeds_ranges[r + 1]
# acc += num
# print(num)
# print(f'seeds: {acc}')
# parse ranges
maps = []
count = 0
cur_list = []
for line in input_lines[2:]:
if line == '':
count += 1
maps.append(cur_list)
elif line.endswith(':'):
cur_list = []
else:
dest, source, length = line.split(' ')
# print(f'parsed dest: {dest} source: {source} len: {length}')
cur_list.append((int(dest), int(source), int(length)))
maps.append(cur_list)
min_location = 1917300386
for r in range(0, len(seeds_ranges), 2):
# print(r)
for s in range(seeds_ranges[r], seeds_ranges[r] + seeds_ranges[r+1]):
location = s
for m in maps:
for r in m:
old = location
if r[1] <= location < (r[1] + r[2]):
location = r[0] + (location - r[1])
break
if location < min_location:
min_location = location
print(f'{len(seeds)} seeds')
# print(f'seeds: {seeds}')
print(min_location)