diff --git a/2015/days/09/part2/Cargo.toml b/2015/days/09/part2/Cargo.toml new file mode 100644 index 0000000..d85b608 --- /dev/null +++ b/2015/days/09/part2/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "part1" +version = "0.1.0" +edition = "2021" + +[dependencies] diff --git a/2015/days/09/part2/src/main.rs b/2015/days/09/part2/src/main.rs new file mode 100644 index 0000000..8d27c6b --- /dev/null +++ b/2015/days/09/part2/src/main.rs @@ -0,0 +1,92 @@ +use std::collections::HashMap; + +fn parse_graph(string: &str) -> Vec> { + let mut n = 0; + let mut node_to_index: HashMap = HashMap::new(); + for item in string.lines() { + let mut parts = item.split(" "); + let city_from = parts.next().unwrap(); + parts.next(); + let city_to = parts.next().unwrap(); + if !node_to_index.contains_key(city_from) { + node_to_index.insert(city_from.to_string().clone(), n); + n += 1; + } + if !node_to_index.contains_key(city_to) { + node_to_index.insert(city_to.to_string().clone(), n); + n += 1; + } + } + let mut graph: Vec> = vec![vec![0; n]; n]; + for item in string.lines() { + let mut parts = item.split(" "); + let city_from = parts.next().unwrap(); + parts.next(); + let city_to = parts.next().unwrap(); + parts.next(); + let distance = parts.next().unwrap(); + let distance: u64 = distance.parse().unwrap(); + let u = *node_to_index.get(city_from).unwrap(); + let v = *node_to_index.get(city_to).unwrap(); + graph[u][v] = distance; + graph[v][u] = distance; + } + return graph; +} + +fn all_permutations(n: usize) -> Vec> { + let mut c: Vec = vec![0; n]; + let mut permutations: Vec> = Vec::new(); + let mut permutation: Vec = Vec::new(); + for i in 0..n { + permutation.push(i); + } + permutations.push(permutation.clone()); + + let mut i = 1; + while i < n { + if c[i] < i { + if i % 2 == 0 { + let tmp = permutation[0]; + permutation[0] = permutation[i]; + permutation[i] = tmp; + } else { + let tmp = permutation[c[i]]; + permutation[c[i]] = permutation[i]; + permutation[i] = tmp; + } + permutations.push(permutation.clone()); + c[i] += 1; + i = 1; + } else { + c[i] = 0; + i += 1; + } + } + permutations +} + +fn longest_distance_brute_force(graph: &Vec>) -> u64 { + let mut max_distance: u64 = 0; + for permutation in all_permutations(graph.len()) { + let mut distance = 0; + for i in 0..(graph.len() - 1) { + let u = permutation[i]; + let v = permutation[i+1]; + let d = graph[u][v]; + distance += d; + } + if distance > max_distance { + max_distance = distance; + } + } + max_distance +} + +fn main() -> std::io::Result<()> { + let string = std::io::read_to_string(std::io::stdin()).unwrap(); + let graph = parse_graph(&string); + let max_distance = longest_distance_brute_force(&graph); + println!("{}", max_distance); + Ok(()) +}