Skip to content

Commit 3865f80

Browse files
authored
Update algorithm10.rs
1 parent 53fb071 commit 3865f80

File tree

1 file changed

+24
-7
lines changed

1 file changed

+24
-7
lines changed

exercises/algorithm/algorithm10.rs

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
/*
2-
graph
3-
This problem requires you to implement a basic graph functio
2+
graph
3+
This problem requires you to implement a basic graph functio
44
*/
5-
// I AM NOT DONE
65

76
use std::collections::{HashMap, HashSet};
87
use std::fmt;
@@ -29,16 +28,34 @@ impl Graph for UndirectedGraph {
2928
&self.adjacency_table
3029
}
3130
fn add_edge(&mut self, edge: (&str, &str, i32)) {
32-
//TODO
31+
let (from, to, weight) = edge;
32+
33+
self.add_node(from);
34+
self.add_node(to);
35+
36+
self.adjacency_table_mutable()
37+
.get_mut(from)
38+
.unwrap()
39+
.push((to.to_string(), weight));
40+
41+
self.adjacency_table_mutable()
42+
.get_mut(to)
43+
.unwrap()
44+
.push((from.to_string(), weight));
3345
}
3446
}
3547
pub trait Graph {
3648
fn new() -> Self;
3749
fn adjacency_table_mutable(&mut self) -> &mut HashMap<String, Vec<(String, i32)>>;
3850
fn adjacency_table(&self) -> &HashMap<String, Vec<(String, i32)>>;
3951
fn add_node(&mut self, node: &str) -> bool {
40-
//TODO
41-
true
52+
let table = self.adjacency_table_mutable();
53+
if table.contains_key(node) {
54+
false
55+
} else {
56+
table.insert(node.to_string(), Vec::new());
57+
true
58+
}
4259
}
4360
fn add_edge(&mut self, edge: (&str, &str, i32)) {
4461
//TODO
@@ -81,4 +98,4 @@ mod test_undirected_graph {
8198
assert_eq!(graph.edges().contains(edge), true);
8299
}
83100
}
84-
}
101+
}

0 commit comments

Comments
 (0)