Advent 2015 Day 7, 8 & 9 Parts 1 & 2
This commit is contained in:
parent
96b06c7bee
commit
de1a181ba5
40 changed files with 1158 additions and 0 deletions
55
advent_of_code_2015/src/day9/part1.rs
Normal file
55
advent_of_code_2015/src/day9/part1.rs
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
fn generate_routes(current: String, mut destinations: HashSet<String>) -> Vec<Vec<String>> {
|
||||
destinations.remove(¤t);
|
||||
let mut routes = Vec::new();
|
||||
|
||||
if destinations.is_empty() {
|
||||
routes.push([current].to_vec());
|
||||
return routes;
|
||||
}
|
||||
|
||||
for destination in destinations.iter() {
|
||||
routes.append(&mut generate_routes(destination.clone(), destinations.clone()));
|
||||
}
|
||||
|
||||
for route in routes.iter_mut() {
|
||||
route.push(current.clone());
|
||||
}
|
||||
|
||||
routes
|
||||
}
|
||||
|
||||
pub fn solve(input: &str) {
|
||||
let mut distances: HashMap<String, HashMap<String, u64>> = HashMap::new();
|
||||
|
||||
input.lines().for_each(|line| {
|
||||
let (from, tail) = line.split_once(" to ").unwrap();
|
||||
let (to, distance) = tail.split_once(" = ").unwrap();
|
||||
|
||||
distances.entry(from.into()).or_default().insert(to.to_string(), distance.parse().unwrap());
|
||||
distances.entry(to.into()).or_default().insert(from.to_string(), distance.parse().unwrap());
|
||||
});
|
||||
|
||||
let cities = distances.keys().cloned().collect::<HashSet<_>>();
|
||||
let mut routes: Vec<Vec<String>> = Vec::new();
|
||||
|
||||
for city in cities.iter() {
|
||||
routes.append(&mut generate_routes(city.clone(), cities.clone()));
|
||||
}
|
||||
|
||||
|
||||
let route_lengths = routes.iter().map(|route| {
|
||||
let mut distance = 0u64;
|
||||
for idx in 0..(route.len() - 1) {
|
||||
distance += distances[&route[idx]][&route[idx + 1]];
|
||||
}
|
||||
distance
|
||||
}).collect::<Vec<_>>();
|
||||
|
||||
// for (route, length) in routes.iter().zip(route_lengths) {
|
||||
// println!("route: {route:?}, distance: {length}");
|
||||
// }
|
||||
|
||||
println!("shortest route: {}", route_lengths.iter().min().unwrap());
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue