day 9: part 2: rust

This commit is contained in:
Samuel Ortion 2024-12-04 13:46:50 +01:00
parent 612bd4313f
commit 586ea78d86
Signed by: sortion
GPG Key ID: 9B02406F8C4FB765
2 changed files with 98 additions and 0 deletions

View File

@ -0,0 +1,6 @@
[package]
name = "part1"
version = "0.1.0"
edition = "2021"
[dependencies]

View File

@ -0,0 +1,92 @@
use std::collections::HashMap;
fn parse_graph(string: &str) -> Vec<Vec<u64>> {
let mut n = 0;
let mut node_to_index: HashMap<String, usize> = 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<u64>> = 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<Vec<usize>> {
let mut c: Vec<usize> = vec![0; n];
let mut permutations: Vec<Vec<usize>> = Vec::new();
let mut permutation: Vec<usize> = 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 shortest_distance_brute_force(graph: &Vec<Vec<u64>>) -> u64 {
let mut min_distance: u64 = u64::MAX;
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 < min_distance {
min_distance = distance;
}
}
min_distance
}
fn main() -> std::io::Result<()> {
let string = std::io::read_to_string(std::io::stdin()).unwrap();
let graph = parse_graph(&string);
let min_distance = shortest_distance_brute_force(&graph);
println!("{}", min_distance);
Ok(())
}