Skip to content

Commit 35e8650

Browse files
committed
wip: bisect nums instead of ranges
There are fewer ranges than numbers, so that already gives a speedup. Additionally, we can find multiple fresh products from a single range, which would otherwise require n searches through the ranges.
1 parent c1f19ad commit 35e8650

File tree

1 file changed

+27
-14
lines changed

1 file changed

+27
-14
lines changed

src/year2025/day05.rs

Lines changed: 27 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -32,22 +32,35 @@ pub fn parse(input: &str) -> Input {
3232
(merged, nums)
3333
}
3434

35+
// pub fn part1((ranges, nums): &Input) -> usize {
36+
// nums.iter()
37+
// .filter(|&&n| {
38+
// ranges
39+
// .binary_search_by(|r| {
40+
// if n < r.start {
41+
// std::cmp::Ordering::Greater
42+
// } else if n > r.end {
43+
// std::cmp::Ordering::Less
44+
// } else {
45+
// std::cmp::Ordering::Equal
46+
// }
47+
// })
48+
// .is_ok()
49+
// })
50+
// .count()
51+
// }
52+
3553
pub fn part1((ranges, nums): &Input) -> usize {
36-
nums.iter()
37-
.filter(|&&n| {
38-
ranges
39-
.binary_search_by(|r| {
40-
if n < r.start {
41-
std::cmp::Ordering::Greater
42-
} else if n > r.end {
43-
std::cmp::Ordering::Less
44-
} else {
45-
std::cmp::Ordering::Equal
46-
}
47-
})
48-
.is_ok()
54+
println!("{} {}", ranges.len(), nums.len());
55+
ranges
56+
.iter()
57+
.map(|r| {
58+
let start = nums.binary_search(&r.start).unwrap_or_else(|e| e);
59+
let end = nums.binary_search(&r.end).unwrap_or_else(|e| e);
60+
61+
end - start
4962
})
50-
.count()
63+
.sum()
5164
}
5265

5366
pub fn part2((ranges, _): &Input) -> u64 {

0 commit comments

Comments
 (0)