Advent of code d5
This is the first one where I've had to change a solution for performance. The logic here was fairly straight forward. The challenge was getting the program to complete before new years eve.
import traceback
ranges = []
ids = []
result = 0
try:
with open("d5.txt", "r") as f:
in_ids = False
for line in f.readlines():
if not line.strip():
in_ids = True
elif in_ids:
ids.append(int(line))
else:
[min, max] = line.split("-")
ranges.append([int(min), int(max)])
ranges.sort(key=lambda x : x[0])
# phase 2
count = 0
[min, max] = ranges[0]
for [next_min, next_max] in ranges[1:]:
if next_min <= max:
max = next_max if next_max > max else max
else:
count += (max + 1 - min)
min, max = next_min, next_max
count += (max + 1 - min)
print(count)
# phase 1
for id in ids:
id = int(id)
for [min, max] in ranges:
if min <= id and max >= id:
result += 1
break
except Exception as e:
traceback.print_exc()
print(result)