---cargo [dependencies] slotmap = "1" --- use slotmap::SlotMap; use std::collections::HashMap; static CONTENT: &'static str = include_str!("./inputs/08_1.txt"); fn main() { let boxes: Vec<(usize, usize, usize)> = CONTENT.lines().map(|l| l.trim()).filter(|l| !l.is_empty()).map(|l| { let (first, rest) = l.split_once(',').unwrap(); let (second, third) = rest.split_once(',').unwrap(); let first = first.parse::().unwrap(); let second = second.parse::().unwrap(); let third = third.parse::().unwrap(); (first, second, third) }).collect(); let mut circuits = SlotMap::<_, Vec<(usize, usize, usize)>>::new(); let mut box_circuits = HashMap::<(usize, usize, usize), slotmap::DefaultKey>::new(); println!("Boxes\n{:?}", boxes); let mut distances: Vec<_> = boxes.iter() .flat_map(|s| core::iter::repeat(s).zip(boxes.iter())) .filter(|(s, t)| s != t) .filter(|(s, t)| ((s.0.pow(2) + s.1.pow(2) + s.2.pow(2)) as f64).sqrt() < ((t.0.pow(2) + t.1.pow(2) + t.2.pow(2)) as f64).sqrt()) .map(|(s, t)| (s, t, ((s.0.abs_diff(t.0).pow(2) + s.1.abs_diff(t.1).pow(2) + s.2.abs_diff(t.2).pow(2)) as f64).sqrt())) .collect(); distances.sort_by(|(_, _, d1), (_, _, d2)| d2.partial_cmp(d1).unwrap()); // println!("Distances\n{:#?}", distances); for _ in 0..1000 { let (first, second, distance) = distances.pop().unwrap(); println!("Connecting:\n\t{:?} <=> {:?}", first, second); let first_circuit = box_circuits.get(first); let second_circuit = box_circuits.get(second); println!("\tFirst Circuit: {:?}", first_circuit); println!("\tSecond Circuit: {:?}", second_circuit); match (first_circuit.copied(), second_circuit.copied()) { (Some(fc), Some(sc)) if fc == sc => {} (Some(fc), Some(sc)) => { let second_boxes = circuits.remove(sc).unwrap(); let first_boxes = circuits.get_mut(fc).unwrap(); for b in second_boxes { first_boxes.push(b); box_circuits.insert(b, fc); } }, (Some(fc), None) => { circuits.get_mut(fc).unwrap().push(*second); box_circuits.insert(*second, fc); }, (None, Some(sc)) => { circuits.get_mut(sc).unwrap().push(*first); box_circuits.insert(*first, sc); }, (None, None) => { let circuit = circuits.insert(vec![*first, *second]); box_circuits.insert(*first, circuit); box_circuits.insert(*second, circuit); println!("\tCreated Circuit: {:?}", circuit); } }; } let mut circuit_list: Vec<_> = circuits.iter().map(|(k, v)| (k, v.len())).collect(); circuit_list.sort_by_key(|(_, v)| core::cmp::Reverse(*v)); println!("Circuits: {:?}", circuit_list); let result = circuit_list.iter().take(3).map(|(_, v)| *v).product::(); println!("Result: {:?}", result); }