-
Notifications
You must be signed in to change notification settings - Fork 0
/
day25.rs
206 lines (182 loc) · 6.6 KB
/
day25.rs
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
#![feature(iter_next_chunk)]
use std::cmp::{max, min};
use std::collections::{BinaryHeap, HashMap, HashSet, VecDeque};
use std::{i32, mem};
use linked_hash_map::LinkedHashMap;
use priority_queue::PriorityQueue;
use rustc_hash::FxHashSet;
pub(crate) fn day25() {
let raw_str =
r###"jqt: rhn xhk nvd
rsh: frs pzl lsr
xhk: hfx
cmg: qnr nvd lhk bvb
rhn: xhk bvb hfx
bvb: xhk hfx
pzl: lsr hfx nvd
qnr: nvd
ntq: jqt hfx bvb xhk
nvd: lhk
lsr: lhk
rzs: qnr cmg lsr rsh
frs: qnr lhk lsr"###;
let example_lines: Vec<&str> = raw_str.lines().collect();
// convert example lines to String
let example_lines: Vec<String> =
example_lines.iter().map(|s| s.to_string()).collect();
//part1(example_lines);
let input = std::fs::read_to_string("./inputs/day25.txt").unwrap();
//// split input into lines
let input: Vec<String> = input.lines().map(|s| s.to_string()).collect();
part1(input);
}
fn part1(lines: Vec<String>) {
// for the first part I basically cheated by using visualisation
// that visualization was generated by this python from Chat GPT:
/*
```python
import networkx as nx
import matplotlib.pyplot as plt
import sys
def draw_graph(filename):
# Create a new graph
G = nx.DiGraph() # Using a directed graph
# Read the file and add edges to the graph
with open(filename, 'r') as file:
for line in file:
node, neighbors = line.strip().split(': ')
neighbors = neighbors.split(' ')
for neighbor in neighbors:
G.add_edge(node, neighbor)
G.add_edge(neighbor, node) # Add the reverse direction
# Draw the graph
nx.draw(G, with_labels=True, node_color='lightblue', font_size=10, node_size=700, arrows=True)
plt.show()
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: python script.py <filename>")
sys.exit(1)
filename = sys.argv[1]
draw_graph(filename)
*/
/*
jqt: rhn xhk nvd
rsh: frs pzl lsr
xhk: hfx
cmg: qnr nvd lhk bvb
rhn: xhk bvb hfx
bvb: xhk hfx
pzl: lsr hfx nvd
qnr: nvd
ntq: jqt hfx bvb xhk
nvd: lhk
lsr: lhk
rzs: qnr cmg lsr rsh
frs: qnr lhk lsr
*/
// let's firstly build a bi-directional graph
let graph = build_graph(lines);
println!("Graph: {:?}", graph);
// Now we want to find two groups,
// that are separated by exactly tree edges.
// We need an algorithm to split graph into two groups
// and then find a split that is separated by exactly three edges.
// let's just brute force it
// consider every possible 3 edges are the split
// and check that graph is split into two groups by BFS
// let's build vertices list from graph
let mut vertices_set: HashSet<String> = HashSet::new();
for (node, children) in &graph {
vertices_set.insert(node.clone());
for child in children {
vertices_set.insert(child.clone());
}
}
let vertices_list: Vec<String> = vertices_set.into_iter().collect();
// let's build edges list from graph
let mut edges_set: HashSet<(String, String)> = HashSet::new();
for (node, children) in &graph {
for child in children {
// let sort (node, child) pair to prevent duplicates
edges_set.insert(
(min(node.clone(), child.clone()),
max(node.clone(), child.clone())));
}
}
let mut edges_list: Vec<(String, String)> = edges_set.into_iter().collect();
let first_edge = ("ljl".to_string(), "xhg".to_string());
let second_edge = ("vgs".to_string(), "xjb".to_string());
let third_edge = ("ffj".to_string(), "lkm".to_string());
let split = vec![first_edge.clone(), second_edge.clone(), third_edge.clone()];
let split_set: HashSet<(String, String)> = split.iter().map(|(a, b)| (a.clone(), b.clone())).collect();
// now run BfS twice to check that graph is split into two groups
// if edges are in split_set, ignore them
let mut visited: HashSet<String> = HashSet::new();
let mut queue: VecDeque<String> = VecDeque::new();
// we can start from edge[k] nodes
// because we know that they are in different groups
queue.push_back(first_edge.clone().0.clone());
while let Some(node) = queue.pop_front() {
if visited.contains(&node) {
continue;
}
visited.insert(node.clone());
println!("node: {}", node);
for child in &graph[&node] {
// sort (node, child) pair to prevent duplicates
let pair = (min(node.clone(), child.clone()),
max(node.clone(), child.clone()));
if !split_set.contains(&pair) {
queue.push_back(child.clone());
}
}
}
// ok, now do BFS from another node
let mut visited_2: HashSet<String> = HashSet::new();
let mut queue_2: VecDeque<String> = VecDeque::new();
queue_2.push_back(first_edge.clone().1.clone());
while let Some(node) = queue_2.pop_front() {
if visited_2.contains(&node) {
continue;
}
visited_2.insert(node.clone());
for child in &graph[&node] {
// sort (node, child) pair to prevent duplicates
let pair = (min(node.clone(), child.clone()),
max(node.clone(), child.clone()));
if !split_set.contains(&pair) {
queue_2.push_back(child.clone());
}
}
}
// now let's check that visited and visited_2 contain all vertices
// check two visited sets are not intersecting
let intersection = visited.intersection(&visited_2).collect::<Vec<&String>>();
let not_intersected = intersection.len() == 0;
let all_visited = visited.len() + visited_2.len() == vertices_list.len();
println!(" len1: {}, len2: {}, len3: {}", visited.len(), visited_2.len(), vertices_list.len());
if !all_visited || !not_intersected {
panic!("Something is wrong");
}
let mut res = 0;
res = visited.len() * visited_2.len();
// 2024929 too high
// 506202
println!("Part 1: {}", res);
}
fn build_graph(lines: Vec<String>) -> HashMap<String, Vec<String>> {
let mut graph: HashMap<String, Vec<String>> = HashMap::new();
for line in lines {
let mut parts = line.split(": ");
let node = parts.next().unwrap().to_string();
let children: Vec<String> = parts.next().unwrap()
.split(" ").map(|s| s.to_string()).collect();
for child in &children {
graph.entry(child.clone()).or_insert(vec![]).push(node.clone());
graph.entry(node.clone()).or_insert(vec![]).push(child.clone());
}
}
graph
}
fn part2(lines: Vec<String>) {
}