1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
use safe_graph::{Graph, NodeTrait};
pub struct FloydWarshallResult<N, E> {
pub path: Graph<N, E>,
pub next: Graph<N, N>,
}
impl<N, E> FloydWarshallResult<N, E>
where
N: NodeTrait,
{
pub(super) fn new(path: Graph<N, E>, next: Graph<N, N>) -> Self {
Self { path, next }
}
pub fn get_path_rate(&self, a: N, b: N) -> Option<&E> {
self.path.edge_weight(a, b)
}
pub fn collect_path_nodes(&self, a: N, b: N) -> Vec<N> {
let next = self.next.edge_weight(a, b);
match next {
Some(&n) => {
let mut nodes = vec![a];
self.collect_path_middle(n, b, &mut nodes);
nodes.push(b);
nodes
}
None => return vec![],
}
}
fn collect_path_middle(&self, mut next: N, end: N, nodes: &mut Vec<N>) {
while next != end {
nodes.push(next);
if nodes.len() > self.path.node_count() {
break;
}
let new_next = self.next.edge_weight(next, end);
match new_next {
Some(&n) => next = n,
None => break,
}
}
}
}
#[cfg(test)]
mod tests {
use crate::result::FloydWarshallResult;
use safe_graph::Graph;
#[test]
fn new() {
let path: Graph<&str, f32> = Graph::new();
let rate: Graph<&str, &str> = Graph::new();
let _result: FloydWarshallResult<&str, f32> = FloydWarshallResult::new(path, rate);
}
#[test]
fn get_path_rate() {
let mut path: Graph<&str, f32> = Graph::new();
let rate: Graph<&str, &str> = Graph::new();
let a = "a";
let b = "b";
let weight = 12.4;
path.add_edge(a, b, weight);
let result: FloydWarshallResult<&str, f32> = FloydWarshallResult::new(path, rate);
assert_eq!(result.get_path_rate(a, b), Some(&weight));
}
#[test]
fn collect_path_nodes() {
let mut path: Graph<&str, f32> = Graph::new();
let mut rate: Graph<&str, &str> = Graph::new();
let w_a_b = 1.2;
let w_a_c = 4.2;
let w_b_d = 0.2;
let w_c_d = 3.3;
path.add_edge("a", "b", w_a_b);
path.add_edge("a", "c", w_a_c);
path.add_edge("b", "d", w_b_d);
path.add_edge("c", "d", w_c_d);
path.add_edge("a", "d", w_a_b + w_b_d);
rate.add_edge("a", "b", "b");
rate.add_edge("a", "c", "c");
rate.add_edge("b", "d", "d");
rate.add_edge("c", "d", "d");
rate.add_edge("a", "d", "d");
rate.add_edge("a", "d", "b");
rate.add_edge("b", "d", "d");
let result: FloydWarshallResult<&str, f32> = FloydWarshallResult::new(path, rate);
assert_eq!(result.get_path_rate("a", "b"), Some(&w_a_b));
assert_eq!(result.collect_path_nodes("a", "b"), vec!["a", "b"]);
assert_eq!(result.get_path_rate("a", "d"), Some(&(w_a_b + w_b_d)));
assert_eq!(result.collect_path_nodes("a", "d"), vec!["a", "b", "d"]);
}
}