-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhashmap_graph_utils.rs
More file actions
85 lines (80 loc) · 2.48 KB
/
hashmap_graph_utils.rs
File metadata and controls
85 lines (80 loc) · 2.48 KB
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
use crate::graph_utils::vec_graph_utils::VecGraph;
use std::collections::{HashMap, HashSet};
use std::io::Write;
pub type HashmapGraph = HashMap<u32, HashSet<u32>>;
pub fn hashmap_of_vec(vec: &VecGraph) -> HashmapGraph {
vec.iter()
.enumerate()
.map(|(id, parents)| {
(
id as u32,
parents.iter().map(|&v| v as u32).collect::<HashSet<_>>(),
)
})
.collect::<HashMap<_, _>>()
}
pub fn filtered_hashmap_of_vec(graph: &VecGraph, kept_vertexes: &HashSet<usize>) -> HashmapGraph {
graph
.iter()
.enumerate()
.filter(|(id, _)| kept_vertexes.contains(id))
.map(|(id, parents)| {
(
id as u32,
parents
.iter()
.filter(|&v| kept_vertexes.contains(v))
.map(|&v| v as u32)
.collect::<HashSet<_>>(),
)
})
.collect::<HashMap<_, _>>()
}
pub fn remove_vertex(vertex: u32, graph: &mut HashmapGraph, reversed: &mut HashmapGraph) -> bool {
if graph.contains_key(&vertex) {
let parents = graph.remove(&vertex).unwrap();
let children = reversed.remove(&vertex).unwrap();
for parent in parents {
reversed.get_mut(&parent).unwrap().remove(&vertex);
}
for child in children {
graph.get_mut(&child).unwrap().remove(&vertex);
}
true
} else {
false
}
}
pub fn export_as_csv(
graph: &HashmapGraph,
name_from_id: Option<&Vec<String>>,
separator: &str,
path: &str,
) {
let write_item = |id: usize, content: &mut String| {
if let Some(name_from_id) = name_from_id {
assert!(!name_from_id[id].contains(separator));
content.push_str(&name_from_id[id]);
} else {
content.push_str(&id.to_string());
}
};
let mut file = std::fs::File::create(path).unwrap();
let mut is_first_line = true;
for (&id, parents) in graph {
let mut content = String::new();
if is_first_line {
is_first_line = false;
} else {
content += "\n";
}
write_item(id as usize, &mut content);
content += separator;
for &parent in parents {
write_item(parent as usize, &mut content);
content += separator;
}
content.pop(); // Removes trailing separator
file.write_all(content.as_bytes()).unwrap();
}
}