Skip to content

Commit 16fdf12

Browse files
committed
refactor(10/2024): extract generic solve function and remove duplication
1 parent bb8eab8 commit 16fdf12

File tree

1 file changed

+13
-33
lines changed

1 file changed

+13
-33
lines changed

src/solutions/year2024/day10.rs

Lines changed: 13 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,25 @@
11
use crate::solutions::Solution;
22
use crate::utils::grid::Grid;
3+
use crate::utils::point::Point;
34
use itertools::Itertools;
45

56
pub struct Day10;
67

78
impl Solution for Day10 {
89
fn part_one(&self, input: &str) -> String {
9-
let grid: Grid<i16> = Grid::from_custom(input.trim(), |c| {
10-
c.to_digit(10).map(|x| x as i16).unwrap_or(-1)
11-
});
12-
13-
grid.get_all_positions(&0)
14-
.iter()
15-
.map(|p| {
16-
let mut current = 0;
17-
let mut current_points = vec![*p];
18-
19-
while current < 9 {
20-
let next = current + 1;
21-
22-
current_points = current_points
23-
.iter()
24-
.flat_map(|point| {
25-
point.adjacent().into_iter().filter(|next_point| {
26-
grid.get_for_point(next_point)
27-
.is_some_and(|value| value == &next)
28-
})
29-
})
30-
.unique()
31-
.collect();
32-
33-
current = next;
34-
}
35-
36-
current_points.len()
37-
})
38-
.sum::<usize>()
39-
.to_string()
10+
self.solve(input, |points| points.into_iter().unique().collect())
4011
}
4112

4213
fn part_two(&self, input: &str) -> String {
14+
self.solve(input, |points| points)
15+
}
16+
}
17+
18+
impl Day10 {
19+
fn solve<F>(&self, input: &str, modify_points: F) -> String
20+
where
21+
F: Fn(Vec<Point>) -> Vec<Point>,
22+
{
4323
let grid: Grid<i16> = Grid::from_custom(input.trim(), |c| {
4424
c.to_digit(10).map(|x| x as i16).unwrap_or(-1)
4525
});
@@ -53,17 +33,17 @@ impl Solution for Day10 {
5333
while current < 9 {
5434
let next = current + 1;
5535

56-
current_points = current_points
36+
let next_points: Vec<Point> = current_points
5737
.iter()
5838
.flat_map(|point| {
5939
point.adjacent().into_iter().filter(|next_point| {
6040
grid.get_for_point(next_point)
6141
.is_some_and(|value| value == &next)
6242
})
6343
})
64-
// .unique()
6544
.collect();
6645

46+
current_points = modify_points(next_points);
6747
current = next;
6848
}
6949

0 commit comments

Comments
 (0)