Ben Yafai

Advent Of Code

5th December 2023

2023 - Day 5

If You Give A Seed A Fertilizer

Today's challenge is certainly an interesting one.

We had to map values multiple times to new values, ending with a final value. The lowest final value overall was the answer. Honestly, it was pretty confusing, but I got there eventually.

I first processed each line and ran some regex to get my working values/ranges

Code

As I built up the map array, I let it dynamically create the source and destination names so I didn't have to manually type each one.

I then ran a foreach on the seeds and maps, identifying if the source number fell within the mapped range. If the number was not in the range, then there was no change, otherwise I'd then have to identify the difference between the source and destination range and apply that to the seed's number.

I ended up adding a boolean for when I had found a working range as I didn't realise I was applying a change, then falling into a new range and applying a further change. That made me scratch my head a little.

Code


Part two is a lot tougher! Now the seed numbers are ranges just like our maps were, and here's the first six numbers:

seeds: 3082872446 316680412 2769223903 74043323 4131958457 99539464

That means our start number is 3082872446 and we have a range of 316680412. Now, that alone means we now have 316 million seed numbers in our first range, 74 million in the next range, and so on. I totted it up, we have 2,207,992,808 seeds to work through... 2 billion!

I first decided to run a for loop and test each seed number individually. I hit memory limits. So I stopped tracking every result so I could run a min() later. I just calulated each time if it was lower and stored it for later.

Then I hit PHP's execution time limit. I set it to 3600 seconds (1 hour!) and still it timed out.

I need to think of a better solution, until then, only 1 star today.

My full responses are found on GitHub