finish 82

This commit is contained in:
Dr. Matthias Ratajczak
2022-09-27 14:05:32 +02:00
parent 6da8e3d651
commit f545a592bd
3 changed files with 22 additions and 13 deletions
+9 -7
View File
@@ -17,14 +17,14 @@ impl AllowedMovements {
}
}
fn get_neighbours_down_right(&self, (x0, y0): &Coordinate) -> Vec<Coordinate> {
vec![(*x0 + 1, *y0), (*x0, *y0 + 1)]
fn get_neighbours_down_right(&self, (x, y): &Coordinate) -> Vec<Coordinate> {
vec![(*x + 1, *y), (*x, *y + 1)]
}
fn get_neighbours_down_right_up(&self, (x0, y0): &Coordinate) -> Vec<Coordinate> {
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<Coordinate> {
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<Coordinate>,
unvisited_without_distance: HashSet<Coordinate>,
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
}
+8 -5
View File
@@ -4,12 +4,12 @@ use std::path::Path;
type Coordinate = (usize, usize);
#[derive(Debug)]
#[derive(Debug, Clone)]
pub struct Matrix {
data: Vec<Vec<Node>>,
}
#[derive(Debug)]
#[derive(Debug, Clone)]
pub struct Node {
value: usize,
distance: Option<usize>,
@@ -76,7 +76,7 @@ impl MatrixTrait<usize> for Matrix {
impl Matrix {
pub fn load(f: &Path) -> Self {
let mut data: Vec<Vec<_>> = fs::read_to_string(f)
let data: Vec<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)
}
}
+5 -1
View File
@@ -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)