diff --git a/lib/dijkstra/src/lib.rs b/lib/dijkstra/src/lib.rs index c907686..c41d2f3 100644 --- a/lib/dijkstra/src/lib.rs +++ b/lib/dijkstra/src/lib.rs @@ -17,14 +17,14 @@ impl AllowedMovements { } } - fn get_neighbours_down_right(&self, (x0, y0): &Coordinate) -> Vec { - vec![(*x0 + 1, *y0), (*x0, *y0 + 1)] + fn get_neighbours_down_right(&self, (x, y): &Coordinate) -> Vec { + vec![(*x + 1, *y), (*x, *y + 1)] } - fn get_neighbours_down_right_up(&self, (x0, y0): &Coordinate) -> Vec { - let mut result = self.get_neighbours_down_right(&(*x0, *y0)); - if *y0 > 0 { - result.push((*x0, *y0 - 1)); + fn get_neighbours_down_right_up(&self, (x, y): &Coordinate) -> Vec { + let mut result = self.get_neighbours_down_right(&(*x, *y)); + if *y > 0 { + result.push((*x, *y - 1)); } result } @@ -51,6 +51,7 @@ pub struct Dijkstra<'a, T> { unvisited_with_distance: HashSet, unvisited_without_distance: HashSet, allowed_movements: AllowedMovements, + start: Coordinate, } impl<'a, T> Debug for Dijkstra<'a, T> { @@ -77,6 +78,7 @@ where unvisited_with_distance, unvisited_without_distance, allowed_movements, + start, } } @@ -103,7 +105,7 @@ where }) .reduce(|(c0, v0), (c1, v1)| if v0 < v1 { (c0, v0) } else { (c1, v1) }) .map(|(c, _)| *c) - .unwrap_or((0, 0)); + .unwrap_or(self.start); self.unvisited_with_distance.remove(&coord); coord } diff --git a/src/euler81/src/lib.rs b/src/euler81/src/lib.rs index 414d0bc..5b473b2 100644 --- a/src/euler81/src/lib.rs +++ b/src/euler81/src/lib.rs @@ -4,12 +4,12 @@ use std::path::Path; type Coordinate = (usize, usize); -#[derive(Debug)] +#[derive(Debug, Clone)] pub struct Matrix { data: Vec>, } -#[derive(Debug)] +#[derive(Debug, Clone)] pub struct Node { value: usize, distance: Option, @@ -76,7 +76,7 @@ impl MatrixTrait for Matrix { impl Matrix { pub fn load(f: &Path) -> Self { - let mut data: Vec> = fs::read_to_string(f) + let data: Vec> = fs::read_to_string(f) .unwrap() .split_whitespace() .map(|line| { @@ -87,8 +87,11 @@ impl Matrix { .collect() }) .collect(); - let mut start = &mut data[0][0]; - start.distance = Some(start.value); Self { data } } + + pub fn set_start(&mut self, (x, y): Coordinate) { + let node = &mut self.data[y][x]; + node.distance = Some(node.value) + } } diff --git a/src/euler82/src/main.rs b/src/euler82/src/main.rs index a3fb774..72d018e 100644 --- a/src/euler82/src/main.rs +++ b/src/euler82/src/main.rs @@ -16,9 +16,13 @@ const FILENAME: &str = "p082_test.txt"; const FILENAME: &str = "p082_matrix.txt"; fn main() { - let mut matrix = Matrix::load(Path::new(FILENAME)); + let matrix_raw = Matrix::load(Path::new(FILENAME)); let mut results = vec![]; + for start in [0].into_iter().cycle().zip(0..LENGTH) { + let mut matrix = matrix_raw.clone(); + matrix.set_start(start); + let mut dijkstra = Dijkstra::new(&mut matrix, AllowedMovements::DownRightUp, start); dijkstra.solve(); let result = (0..LENGTH)