Day 05 - Cafeteria
Language: Rust
Problem https://adventofcode.com/2025/day/5
This one fooled me a bit.
At first it looked like a straightforward parsing exercise, but only part 1 really was. Part 2 quickly proved that brute force is not the way to go.
The input has two sections:
- A list of inclusive ranges like
3-5 - A list of ingredient IDs (one per line)
Part 1 asks how many IDs fall inside any of the ranges. Part 2 asks how many unique IDs are covered by the ranges themselves.
Small wording change, completely different mindset.
Part 1: Nothing fancy here.
I just:
- Parsed the ranges into a vector of
(start, end) - Parsed the IDs
- Checked each ID against all ranges
- Counted the ones that matched
let fresh = ids.filter(|id| {
ranges.iter().any(|(s, e)| id >= s && id <= e)
}).count();
It’s brute force, but the input is small enough that it runs instantly. No reason to complicate it.
Part 2: This is where brute force stops being cute.
We’re asked how many distinct values are covered by the ranges. If ranges overlap, they shouldn’t be counted twice.
My first thought was still brute force. After a few minutes, it was obvious that this was the wrong decision.
The clean solution is to merge intervals:
- Parse all ranges
- Sort them by start value
- Merge overlapping or touching ranges
- Sum the sizes of the merged intervals
Important details: ranges are inclusive, so the size is end - start + 1.
Also, touching ranges must merge, otherwise you undercount.
Merge loop:
ranges.sort_by_key(|&(start, _end)| start);
let (mut merged_start, mut merged_end) = ranges[0];
let mut total_covered = 0;
for (start, end) in ranges.into_iter().skip(1) {
if start <= merged_end + 1 {
if end > merged_end {
merged_end = end;
}
} else {
total_covered += merged_end - merged_start + 1;
merged_start = start;
merged_end = end;
}
}
total_covered += merged_end - merged_start + 1;
Final thoughts As soon as the question becomes about distinct coverage, you’re really solving an interval problem. And once you see it that way, the solution is actually clean and fast.
Solution: https://github.com/Elyrial/AdventOfCode/blob/main/src/solutions/year2025/day05.rs
No C writeup yet.