walky/datastructures/
vecmatrix.rs

1use std::convert::From;
2use std::ops::{Deref, DerefMut};
3
4use crate::datastructures::{AdjacencyMatrix, Graph};
5
6#[derive(Debug, PartialEq)]
7pub struct VecMatrix(Vec<Vec<f64>>);
8
9impl From<Graph> for VecMatrix {
10    fn from(graph: Graph) -> Self {
11        let n: usize = graph.num_vertices();
12        let mut matrix = vec![vec![f64::INFINITY; n]; n];
13        for i in 0..n {
14            let vi = &graph[i];
15            for edge in vi.iter() {
16                let j = edge.to;
17                matrix[i][j] = edge.cost;
18                matrix[j][i] = edge.cost;
19            }
20        }
21        matrix.into()
22    }
23}
24
25impl From<Vec<Vec<f64>>> for VecMatrix {
26    fn from(matrix: Vec<Vec<f64>>) -> Self {
27        VecMatrix(matrix)
28    }
29}
30
31impl Deref for VecMatrix {
32    type Target = Vec<Vec<f64>>;
33    fn deref(&self) -> &Self::Target {
34        &self.0
35    }
36}
37
38impl DerefMut for VecMatrix {
39    fn deref_mut(&mut self) -> &mut Self::Target {
40        &mut self.0
41    }
42}
43
44impl AdjacencyMatrix for VecMatrix {
45    fn from_dim(dim: usize) -> Self {
46        let mut vector = vec![vec![f64::INFINITY; dim]; dim];
47        for (i, neighbours) in vector.iter_mut().enumerate() {
48            neighbours[i] = 0.;
49        }
50        VecMatrix(vector)
51    }
52
53    fn dim(&self) -> usize {
54        self.len()
55    }
56
57    fn get(&self, row: usize, col: usize) -> f64 {
58        self[row][col]
59    }
60
61    fn set(&mut self, row: usize, col: usize, cost: f64) {
62        self[row][col] = cost;
63    }
64}