Skip to main content

aoc/year2025/
day05.rs

1//! # Cafeteria
2//!
3//! We speed things up by first merging ranges. This is possible in `O(n log n)` instead of `O(n²)`
4//! complexity by first sorting the ranges in ascending order of their start.
5//!
6//! Interestingly, part one is harder than part two. We could check every ID against every range,
7//! however this is slow. It's much faster instead to first sort IDs in ascending order,
8//! then for each range use a [binary search](https://en.wikipedia.org/wiki/Binary_search) to count
9//! the number of IDs that it contains. Rust even provides a handy built-in
10//! [`partition_point`] method on slices that returns the index of the first ID not less than
11//! a given value.
12//!
13//! [`partition_point`]: https://doc.rust-lang.org/std/primitive.slice.html#method.partition_point
14use std::ops::Range;
15
16use crate::util::iter::*;
17use crate::util::parse::*;
18
19type Input = (Vec<Range<u64>>, Vec<u64>);
20
21pub fn parse(input: &str) -> Input {
22    let (prefix, suffix) = input.split_once("\n\n").unwrap();
23    let mut ranges: Vec<Range<u64>> =
24        prefix.iter_unsigned().chunk::<2>().map(|[from, to]| from..to + 1).collect();
25    let mut ids: Vec<_> = suffix.iter_unsigned().collect();
26
27    ranges.sort_unstable_by_key(|range| range.start);
28    ids.sort_unstable();
29
30    // Merge ranges together.
31    ranges.dedup_by(|next, range| {
32        if next.start < range.end {
33            range.end = range.end.max(next.end);
34            true
35        } else {
36            false
37        }
38    });
39
40    (ranges, ids)
41}
42
43pub fn part1(input: &Input) -> usize {
44    let (merged, ids) = input;
45    let position = |id| ids.partition_point(|&next| next < id);
46    merged.iter().map(|range| position(range.end) - position(range.start)).sum()
47}
48
49pub fn part2(input: &Input) -> u64 {
50    let (merged, _) = input;
51    merged.iter().map(|range| range.end - range.start).sum()
52}