Skip to content

Commit

Permalink
feat(18/2024): introduce a start builder
Browse files Browse the repository at this point in the history
  • Loading branch information
manhunto committed Dec 20, 2024
1 parent 2282c0c commit e724d17
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 7 deletions.
6 changes: 4 additions & 2 deletions src/solutions/year2024/day18.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::solutions::Solution;
use crate::utils::graphs::a_star::AStar;
use crate::utils::graphs::a_star::AStarBuilder;
use crate::utils::point::Point;
use crate::utils::surface_range::SurfaceRange;
use itertools::Itertools;
Expand Down Expand Up @@ -34,7 +34,9 @@ impl Solution for Day18 {

let distance = |from: Point, to: Point| from.manhattan_distance(&to) as usize;

let a_star = AStar::new(&neighbours, &distance);
let a_star = AStarBuilder::init(&neighbours, &distance)
.memory_size(self.surface.area())
.build();

(a_star.path(start, end).unwrap().len() - 1).to_string()
}
Expand Down
42 changes: 37 additions & 5 deletions src/utils/graphs/a_star.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,30 @@ use std::hash::Hash;
pub struct AStar<'a, T> {
neighbours: &'a dyn Fn(T) -> Vec<T>,
distance: &'a dyn Fn(T, T) -> usize,
memory_size: usize,
}

impl<'a, T> AStar<'a, T> {
pub fn new(neighbours: &'a dyn Fn(T) -> Vec<T>, distance: &'a dyn Fn(T, T) -> usize) -> Self {
pub fn new(
neighbours: &'a dyn Fn(T) -> Vec<T>,
distance: &'a dyn Fn(T, T) -> usize,
memory_size: usize,
) -> Self {
Self {
neighbours,
distance,
memory_size,
}
}

pub fn path(&self, start: T, end: T) -> Option<Vec<T>>
where
T: Hash + Eq + PartialEq + Ord + Copy + Debug,
{
let mut open_set = BinaryHeap::new();
let mut came_from: HashMap<T, T> = HashMap::new();
let mut g_score: HashMap<T, usize> = HashMap::new();
let mut f_score: HashMap<T, usize> = HashMap::new();
let mut open_set = BinaryHeap::with_capacity(self.memory_size);
let mut came_from: HashMap<T, T> = HashMap::with_capacity(self.memory_size);
let mut g_score: HashMap<T, usize> = HashMap::with_capacity(self.memory_size);
let mut f_score: HashMap<T, usize> = HashMap::with_capacity(self.memory_size);

let distance = (self.distance)(start, end);

Expand Down Expand Up @@ -76,3 +82,29 @@ impl<'a, T> AStar<'a, T> {
path
}
}

pub struct AStarBuilder<'a, T> {
neighbours: &'a dyn Fn(T) -> Vec<T>,
distance: &'a dyn Fn(T, T) -> usize,
memory_size: Option<usize>,
}

impl<'a, T> AStarBuilder<'a, T> {
pub fn init(neighbours: &'a dyn Fn(T) -> Vec<T>, distance: &'a dyn Fn(T, T) -> usize) -> Self {
Self {
neighbours,
distance,
memory_size: None,
}
}

pub fn memory_size(mut self, memory_size: usize) -> Self {
self.memory_size = Some(memory_size);

self
}

pub fn build(self) -> AStar<'a, T> {
AStar::new(self.neighbours, self.distance, self.memory_size.unwrap())
}
}

0 comments on commit e724d17

Please sign in to comment.