Skip to content

Commit d1df66f

Browse files
yllmisyllmis
authored andcommitted
update
1 parent 20e4236 commit d1df66f

File tree

7 files changed

+343
-192
lines changed

7 files changed

+343
-192
lines changed

exercises/algorithm/algorithm10.rs

Lines changed: 31 additions & 5 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;
@@ -30,6 +29,19 @@ impl Graph for UndirectedGraph {
3029
}
3130
fn add_edge(&mut self, edge: (&str, &str, i32)) {
3231
//TODO
32+
let (a, b, w) = edge;
33+
34+
self.add_node(a);
35+
self.add_node(b);
36+
37+
self.adjacency_table_mutable()
38+
.get_mut(&a.to_string())
39+
.unwrap()
40+
.push((b.to_string(), w));
41+
self.adjacency_table_mutable()
42+
.get_mut(&b.to_string())
43+
.unwrap()
44+
.push((a.to_string(), w));
3345
}
3446
}
3547
pub trait Graph {
@@ -38,10 +50,24 @@ pub trait Graph {
3850
fn adjacency_table(&self) -> &HashMap<String, Vec<(String, i32)>>;
3951
fn add_node(&mut self, node: &str) -> bool {
4052
//TODO
41-
true
53+
let key = node.to_string();
54+
let table = self.adjacency_table_mutable();
55+
if table.contains_key(&key) {
56+
false
57+
} else {
58+
table.insert(key, Vec::new());
59+
true
60+
}
4261
}
4362
fn add_edge(&mut self, edge: (&str, &str, i32)) {
4463
//TODO
64+
let (src, dst, weight) = edge;
65+
self.add_node(src);
66+
self.add_node(dst);
67+
self.adjacency_table_mutable()
68+
.get_mut(&src.to_string())
69+
.unwrap()
70+
.push((dst.to_string(), weight));
4571
}
4672
fn contains(&self, node: &str) -> bool {
4773
self.adjacency_table().get(node).is_some()
@@ -81,4 +107,4 @@ mod test_undirected_graph {
81107
assert_eq!(graph.edges().contains(edge), true);
82108
}
83109
}
84-
}
110+
}

exercises/algorithm/algorithm4.rs

Lines changed: 35 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,11 @@
11
/*
2-
binary_search tree
3-
This problem requires you to implement a basic interface for a binary tree
2+
binary_search tree
3+
This problem requires you to implement a basic interface for a binary tree
44
*/
55

6-
//I AM NOT DONE
76
use std::cmp::Ordering;
87
use std::fmt::Debug;
98

10-
119
#[derive(Debug)]
1210
struct TreeNode<T>
1311
where
@@ -43,20 +41,32 @@ impl<T> BinarySearchTree<T>
4341
where
4442
T: Ord,
4543
{
46-
4744
fn new() -> Self {
4845
BinarySearchTree { root: None }
4946
}
5047

5148
// Insert a value into the BST
5249
fn insert(&mut self, value: T) {
5350
//TODO
51+
if let Some(ref mut node) = self.root {
52+
node.insert(value);
53+
} else {
54+
self.root = Some(Box::new(TreeNode::new(value)));
55+
}
5456
}
5557

5658
// Search for a value in the BST
5759
fn search(&self, value: T) -> bool {
5860
//TODO
59-
true
61+
let mut current = &self.root;
62+
while let Some(ref node) = current {
63+
match value.cmp(&node.value) {
64+
Ordering::Less => current = &node.left,
65+
Ordering::Greater => current = &node.right,
66+
Ordering::Equal => return true,
67+
}
68+
}
69+
false
6070
}
6171
}
6272

@@ -67,10 +77,26 @@ where
6777
// Insert a node into the tree
6878
fn insert(&mut self, value: T) {
6979
//TODO
80+
match value.cmp(&self.value) {
81+
Ordering::Less => {
82+
if let Some(ref mut left) = self.left {
83+
left.insert(value);
84+
} else {
85+
self.left = Some(Box::new(TreeNode::new(value)));
86+
}
87+
}
88+
Ordering::Greater => {
89+
if let Some(ref mut right) = self.right {
90+
right.insert(value);
91+
} else {
92+
self.right = Some(Box::new(TreeNode::new(value)));
93+
}
94+
}
95+
Ordering::Equal => {}
96+
}
7097
}
7198
}
7299

73-
74100
#[cfg(test)]
75101
mod tests {
76102
use super::*;
@@ -79,24 +105,20 @@ mod tests {
79105
fn test_insert_and_search() {
80106
let mut bst = BinarySearchTree::new();
81107

82-
83108
assert_eq!(bst.search(1), false);
84109

85-
86110
bst.insert(5);
87111
bst.insert(3);
88112
bst.insert(7);
89113
bst.insert(2);
90114
bst.insert(4);
91115

92-
93116
assert_eq!(bst.search(5), true);
94117
assert_eq!(bst.search(3), true);
95118
assert_eq!(bst.search(7), true);
96119
assert_eq!(bst.search(2), true);
97120
assert_eq!(bst.search(4), true);
98121

99-
100122
assert_eq!(bst.search(1), false);
101123
assert_eq!(bst.search(6), false);
102124
}
@@ -105,22 +127,17 @@ mod tests {
105127
fn test_insert_duplicate() {
106128
let mut bst = BinarySearchTree::new();
107129

108-
109130
bst.insert(1);
110131
bst.insert(1);
111132

112-
113133
assert_eq!(bst.search(1), true);
114134

115-
116135
match bst.root {
117136
Some(ref node) => {
118137
assert!(node.left.is_none());
119138
assert!(node.right.is_none());
120-
},
139+
}
121140
None => panic!("Root should not be None after insertion"),
122141
}
123142
}
124-
}
125-
126-
143+
}

exercises/algorithm/algorithm5.rs

Lines changed: 28 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,13 @@
11
/*
2-
bfs
3-
This problem requires you to implement a basic BFS algorithm
2+
bfs
3+
This problem requires you to implement a basic BFS algorithm
44
*/
55

6-
//I AM NOT DONE
76
use std::collections::VecDeque;
87

98
// Define a graph
109
struct Graph {
11-
adj: Vec<Vec<usize>>,
10+
adj: Vec<Vec<usize>>,
1211
}
1312

1413
impl Graph {
@@ -21,21 +20,39 @@ impl Graph {
2120

2221
// Add an edge to the graph
2322
fn add_edge(&mut self, src: usize, dest: usize) {
24-
self.adj[src].push(dest);
25-
self.adj[dest].push(src);
23+
self.adj[src].push(dest);
24+
self.adj[dest].push(src);
2625
}
2726

2827
// Perform a breadth-first search on the graph, return the order of visited nodes
2928
fn bfs_with_return(&self, start: usize) -> Vec<usize> {
30-
31-
//TODO
29+
//TODO
3230

33-
let mut visit_order = vec![];
34-
visit_order
31+
let n = self.adj.len();
32+
if start >= n {
33+
return vec![];
34+
}
35+
36+
let mut visited = vec![false; n];
37+
let mut q: VecDeque<usize> = VecDeque::new();
38+
let mut visited_order = Vec::with_capacity(n);
39+
40+
visited[start] = true;
41+
q.push_back(start);
42+
43+
while let Some(u) = q.pop_front() {
44+
visited_order.push(u);
45+
for &v in &self.adj[u] {
46+
if !visited[v] {
47+
visited[v] = true;
48+
q.push_back(v);
49+
}
50+
}
51+
}
52+
visited_order
3553
}
3654
}
3755

38-
3956
#[cfg(test)]
4057
mod tests {
4158
use super::*;
@@ -84,4 +101,3 @@ mod tests {
84101
assert_eq!(visited_order, vec![0]);
85102
}
86103
}
87-

exercises/algorithm/algorithm6.rs

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,12 @@
11
/*
2-
dfs
3-
This problem requires you to implement a basic DFS traversal
2+
dfs
3+
This problem requires you to implement a basic DFS traversal
44
*/
55

6-
// I AM NOT DONE
76
use std::collections::HashSet;
87

98
struct Graph {
10-
adj: Vec<Vec<usize>>,
9+
adj: Vec<Vec<usize>>,
1110
}
1211

1312
impl Graph {
@@ -19,17 +18,29 @@ impl Graph {
1918

2019
fn add_edge(&mut self, src: usize, dest: usize) {
2120
self.adj[src].push(dest);
22-
self.adj[dest].push(src);
21+
self.adj[dest].push(src);
2322
}
2423

2524
fn dfs_util(&self, v: usize, visited: &mut HashSet<usize>, visit_order: &mut Vec<usize>) {
2625
//TODO
26+
if v >= self.adj.len() || visited.contains(&v) {
27+
return;
28+
}
29+
30+
visited.insert(v);
31+
visit_order.push(v);
32+
33+
for &u in &self.adj[v] {
34+
if !visited.contains(&u) {
35+
self.dfs_util(u, visited, visit_order);
36+
}
37+
}
2738
}
2839

2940
// Perform a depth-first search on the graph, return the order of visited nodes
3041
fn dfs(&self, start: usize) -> Vec<usize> {
3142
let mut visited = HashSet::new();
32-
let mut visit_order = Vec::new();
43+
let mut visit_order = Vec::new();
3344
self.dfs_util(start, &mut visited, &mut visit_order);
3445
visit_order
3546
}
@@ -56,7 +67,7 @@ mod tests {
5667
graph.add_edge(0, 2);
5768
graph.add_edge(1, 2);
5869
graph.add_edge(2, 3);
59-
graph.add_edge(3, 3);
70+
graph.add_edge(3, 3);
6071

6172
let visit_order = graph.dfs(0);
6273
assert_eq!(visit_order, vec![0, 1, 2, 3]);
@@ -67,12 +78,11 @@ mod tests {
6778
let mut graph = Graph::new(5);
6879
graph.add_edge(0, 1);
6980
graph.add_edge(0, 2);
70-
graph.add_edge(3, 4);
81+
graph.add_edge(3, 4);
7182

7283
let visit_order = graph.dfs(0);
73-
assert_eq!(visit_order, vec![0, 1, 2]);
84+
assert_eq!(visit_order, vec![0, 1, 2]);
7485
let visit_order_disconnected = graph.dfs(3);
75-
assert_eq!(visit_order_disconnected, vec![3, 4]);
86+
assert_eq!(visit_order_disconnected, vec![3, 4]);
7687
}
7788
}
78-

0 commit comments

Comments
 (0)