Skip to content

Commit 0fcaec5

Browse files
committed
chore: merge the sum implementations
1 parent 6d5d7c0 commit 0fcaec5

File tree

3 files changed

+36
-24
lines changed

3 files changed

+36
-24
lines changed

aoclp/src/functional.rs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
pub trait PredHelper<T, U> {
2+
fn with_ref(self) -> impl Fn(&T) -> U
3+
where
4+
T: Clone;
5+
}
6+
7+
impl<F, T, U> PredHelper<T, U> for F
8+
where
9+
F: Fn(T) -> U,
10+
{
11+
fn with_ref(self) -> impl Fn(&T) -> U
12+
where
13+
T: Clone,
14+
{
15+
move |x| self(x.clone())
16+
}
17+
}

aoclp/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
33
pub mod captures;
44
pub mod forth;
5+
pub mod functional;
56
pub mod looping;
67
pub mod positioning;
78
pub mod solvers_impl;

aoclp_solutions/src/y2025/day_02.rs

Lines changed: 18 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,39 @@
11
use std::ops::RangeInclusive;
22
use std::str::FromStr;
33

4+
use aoclp::functional::PredHelper;
45
use aoclp::num::Integer;
56
use aoclp::solvers_impl::input::safe_get_input_as_one_vec;
6-
use fancy_regex::Regex;
77
use itertools::Itertools;
88

99
pub fn part_1() -> usize {
10-
match be_fast() {
11-
true => sum_fast(invalid),
12-
false => sum_slow(Regex::new(r"^(\d+)\1$").unwrap()),
13-
}
10+
let pred = invalid;
11+
12+
// Replace `pred` with this for the slow, regex-based approach:
13+
// let re = fancy_regex::Regex::new(r"^(\d+)\1$").unwrap();
14+
// let pred = |id: usize| re.is_match(&id.to_string()).unwrap();
15+
16+
sum(pred)
1417
}
1518

1619
pub fn part_2() -> usize {
17-
match be_fast() {
18-
true => sum_fast(invalid),
19-
false => sum_slow(Regex::new(r"^(\d+)\1+$").unwrap()),
20-
}
21-
}
20+
let pred = invalid_fancy;
21+
22+
// Replace `pred` with this for the slow, regex-based approach:
23+
// let re = fancy_regex::Regex::new(r"^(\d+)\1+$").unwrap();
24+
// let pred = |id: usize| re.is_match(&id.to_string()).unwrap();
2225

23-
fn be_fast() -> bool {
24-
true
26+
sum(pred)
2527
}
2628

27-
fn sum_fast<P>(mut pred: P) -> usize
29+
fn sum<P>(pred: P) -> usize
2830
where
29-
P: FnMut(usize) -> bool,
31+
P: Fn(usize) -> bool,
3032
{
3133
input()
3234
.into_iter()
33-
.flat_map(|range| range.into_iter())
34-
.filter(|id| pred(*id))
35-
.sum()
36-
}
37-
38-
fn sum_slow(re: Regex) -> usize {
39-
input()
40-
.into_iter()
41-
.flat_map(|range| range.into_iter())
42-
.filter(|id| re.is_match(&id.to_string()).unwrap())
35+
.flat_map(<_>::into_iter)
36+
.filter(pred.with_ref())
4337
.sum()
4438
}
4539

0 commit comments

Comments
 (0)