Juha-Matti Santala
Community Builder. Dreamer. Adventurer.

Advent of Code - 2023

This is a solution to Day 5 of Advent of Code 2023.

Day 5: If You Give A Seed A Fertilizer

You take the boat and find the gardener right where you were told he would be: managing a giant "garden" that looks more to you like a farm.

"A water source? Island Island is the water source!" You point out that Snow Island isn't receiving any water.

"Oh, we had to stop the water because we ran out of sand to filter it with! Can't make snow with dirty water. Don't worry, I'm sure we'll get more sand soon; we only turned off the water a few days... weeks... oh no." His face sinks into a look of horrified realization.

"I've been so busy making sure everyone here has food that I completely forgot to check why we stopped getting more sand! There's a ferry leaving soon that is headed over in that direction - it's much faster than your boat. Could you please go check it out?"

You barely have time to agree to this request when he brings up another. "While you wait for the ferry, maybe you can help us with our food production problem. The latest Island Island Almanac just arrived and we're having trouble making sense of it."

The almanac (your puzzle input) lists all of the seeds that need to be planted. It also lists what type of soil to use with each kind of seed, what type of fertilizer to use with each kind of soil, what type of water to use with each kind of fertilizer, and so on. Every type of seed, soil, fertilizer and so on is identified with a number, but numbers are reused by each category - that is, soil 123 and fertilizer 123 aren't necessarily related to each other.

For example:

seeds: 79 14 55 13

seed-to-soil map:
50 98 2
52 50 48

soil-to-fertilizer map:
0 15 37
37 52 2
39 0 15

fertilizer-to-water map:
49 53 8
0 11 42
42 0 7
57 7 4

water-to-light map:
88 18 7
18 25 70

light-to-temperature map:
45 77 23
81 45 19
68 64 13

temperature-to-humidity map:
0 69 1
1 0 69

humidity-to-location map:
60 56 37
56 93 4

The almanac starts by listing which seeds need to be planted: seeds 79, 14, 55, and 13.

The rest of the almanac contains a list of maps which describe how to convert numbers from a source category into numbers in a destination category. That is, the section that starts with seed-to-soil map: describes how to convert a seed number (the source) to a soil number (the destination). This lets the gardener and his team know which soil to use with which seeds, which water to use with which fertilizer, and so on.

Rather than list every source number and its corresponding destination number one by one, the maps describe entire ranges of numbers that can be converted. Each line within a map contains three numbers: the destination range start, the source range start, and the range length.

Consider again the example seed-to-soil map:

50 98 2
52 50 48

The first line has a destination range start of 50, a source range start of 98, and a range length of 2. This line means that the source range starts at 98 and contains two values: 98 and 99. The destination range is the same length, but it starts at 50, so its two values are 50 and 51. With this information, you know that seed number 98 corresponds to soil number 50 and that seed number 99 corresponds to soil number 51.

The second line means that the source range starts at 50 and contains 48 values: 50, 51, ..., 96, 97. This corresponds to a destination range starting at 52 and also containing 48 values: 52, 53, ..., 98, 99. So, seed number 53 corresponds to soil number 55.

Any source numbers that aren't mapped correspond to the same destination number. So, seed number 10 corresponds to soil number 10.

So, the entire list of seed numbers and their corresponding soil numbers looks like this:

seed  soil
0     0
1     1
...   ...
48    48
49    49
50    52
51    53
...   ...
96    98
97    99
98    50
99    51

With this map, you can look up the soil number required for each initial seed number:

  • Seed number 79 corresponds to soil number 81.
  • Seed number 14 corresponds to soil number 14.
  • Seed number 55 corresponds to soil number 57.
  • Seed number 13 corresponds to soil number 13.

The gardener and his team want to get started as soon as possible, so they'd like to know the closest location that needs a seed. Using these maps, find the lowest location number that corresponds to any of the initial seeds. To do this, you'll need to convert each seed number through other categories until you can find its corresponding location number. In this example, the corresponding types are:

  • Seed 79, soil 81, fertilizer 81, water 81, light 74, temperature 78, humidity 78, location 82.
  • Seed 14, soil 14, fertilizer 53, water 49, light 42, temperature 42, humidity 43, location 43.
  • Seed 55, soil 57, fertilizer 57, water 53, light 46, temperature 82, humidity 82, location 86.
  • Seed 13, soil 13, fertilizer 52, water 41, light 34, temperature 34, humidity 35, location 35.

So, the lowest location number in this example is 35.

What is the lowest location number that corresponds to any of the initial seed numbers>>?

Read input

Today's input was multisectioned and different sections needed different handling so I decided to do everything right here instead of using my read_input functionality.

First I split all the sections by empty lines. Then, I read in the seeds which are all the numbers on the first section.

Then for each other section, I parse the destination start, source start and range length attributes for each line and store them into lists.

import re
from collections import namedtuple

Range = namedtuple('Range', ['dest_start', 'source_start', 'range'])


with open('../inputs/day_5.txt') as raw_input:
    data_sections = raw_input.read().split('\n\n')

seeds = [int(seed) for seed in re.findall(r'\d+', data_sections[0].split(': ')[1])]

def process_ranges(section):
    lines = section.split('\n')[1:]
    ranges = []
    for line in lines:
        numbers = [int(value) for value in re.findall(r'\d+', line)]
        ranges.append(Range(*numbers))
    return ranges

seed_to_soil = process_ranges(data_sections[1])
soil_to_fertilizer = process_ranges(data_sections[2])
fertilizer_to_water = process_ranges(data_sections[3])
water_to_light = process_ranges(data_sections[4])
light_to_temperature = process_ranges(data_sections[5])
temperature_to_humidity = process_ranges(data_sections[6])
humidity_to_location = process_ranges(data_sections[7])

ranges = [
    seed_to_soil,
    soil_to_fertilizer,
    fertilizer_to_water,
    water_to_light,
    light_to_temperature,
    temperature_to_humidity,
    humidity_to_location
]

To calculate the location for each seed, I loop through the ranges, find the next correct value for each range and finally keep track of them all to calculate the smallest end result at the end.

def map_to_value(source, r):
    if source >= r.source_start and source <= r.source_start + r.range:
        n = source - r.source_start
        return r.dest_start + n
    else:
        return -1

def calculate_location(seed, ranges):
    source = seed
    for _range in ranges:
        for individual_range in _range:
            potential = map_to_value(source, individual_range)
            if potential != -1:
                source = potential
                break
            else:
                continue
    return source
smallest = None
for seed in seeds:
    location = calculate_location(seed, ranges)
    if not smallest or location < smallest:
        smallest = location

print(f'Solution: {smallest}')
assert smallest == 88151870

Part 2

Everyone will starve if you only plant such a small number of seeds. Re-reading the almanac, it looks like the seeds: line actually describes ranges of seed numbers.

The values on the initial seeds: line come in pairs. Within each pair, the first value is the start of the range and the second value is the length of the range. So, in the first line of the example above:

seeds: 79 14 55 13

This line describes two ranges of seed numbers to be planted in the garden. The first range starts with seed number 79 and contains 14 values: 79, 80, ..., 91, 92. The second range starts with seed number 55 and contains 13 values: 55, 56, ..., 66, 67.

Now, rather than considering four seed numbers, you need to consider a total of 27 seed numbers.

In the above example, the lowest location number can be obtained from seed number 82, which corresponds to soil 84, fertilizer 84, water 84, light 77, temperature 45, humidity 46, and location 46. So, the lowest location number is 46.

Consider all of the initial seed numbers listed in the ranges on the first line of the almanac. What is the lowest location number that corresponds to any of the initial seed numbers?

Oof, this one was tough. I spent an entire Wednesday evening trying to figure this out. I got tipped by a friend to start from the locations and find a matching seed.

I wrote a map_to_prev function that is the inverse of the previous map_to_value and finds the corresponding value in the earlier section of input.

def map_to_prev(dest, r):
    low = r.dest_start
    high = r.dest_start + r.range - 1
    # Any source numbers that aren't mapped
    # correspond to the same destination number.
    if dest < low or dest > high:
        return -1
    else:
        return dest - r.dest_start + r.source_start

Then I did a similar thing with find_seed which is the inverse of find_location. I give it starting location and ranges in reverse order and find a match for each step. If one is not found, keep the value as it is.

def find_seed(location, ranges):
    src = location
    for _range in ranges:
        for individual_range in _range:
            potential = map_to_prev(src, individual_range)
            if potential != -1:
                src = potential
                break
    return src

I needed a way to check if any given number exists as a seed. Since expanding all those ranges would take too much space and looping them processor cycles, I only deal with the lower end and the length.

To check if a seed is in any given seed range, I check if it's within its range.

def get_all_seed_ranges(data_sections):
    seed_range_input = [int(seed) for seed in re.findall(r'\d+', data_sections[0].split(': ')[1])]
    return zip(seed_range_input[::2], seed_range_input[1::2])

def is_valid_seed(seed, seed_ranges):
    for seed_range in seed_ranges:
        if seed_range[0] < seed < seed_range[0] + seed_range[1]:
            return True
    return False

To get the locations, I find the highest value in any given range and create a range from 1 to that value.

location_ranges = ranges[-1]

# max() would work here without the lambda
# because the first value in the Range happens
# to be what we want.
#
# I wanted to make it explicit though
highest_location_range = max(location_ranges, key=lambda range: range.dest_start)
max_location = highest_location_range.dest_start + highest_location_range.range
all_locations = range(1, max_location)

seed_ranges = list(get_all_seed_ranges(data_sections))

To find the smallest location that maps to a seed, I start from 1 and loop until I find a matching seed and then stop.

This takes roughly 40 seconds to run so there's probably a neater way to solve it in way less time. But it doesn't crash my computer and doesn't take more a minute to run so I'm okay with this.

part_2 = None

for location in all_locations:
    # `ranges[-1::-1]` skips the locations range and reverses list
    seed = find_seed(location, ranges[-1::-1])
    if is_valid_seed(seed, seed_ranges):
        print(f'Found {seed=} at {location=}')
        part_2 = location
        break
print(f'Solution: {part_2}')
assert part_2 == 2008785

Two stars!

Finally, managed to wrap this up before I got too much behind. We're now at 8/50 stars.