From: alex <> Date: Mon, 8 Dec 2025 18:11:42 +0000 (+0100) Subject: day08: part2 X-Git-Url: https://aoc.elinar.fr/?a=commitdiff_plain;h=de7164079e5eeed35608870146ec5dc43280fee7;p=aoc_2025 day08: part2 --- diff --git a/src/day08.rs b/src/day08.rs index cdd2abb..ba314cf 100644 --- a/src/day08.rs +++ b/src/day08.rs @@ -95,11 +95,63 @@ impl Puzzle { circuits.sort_by(|a, b| b.cmp(a)); circuits.iter().take(3).product() } + + fn part2(&self) -> i64 { + let mut connections: Vec<(i64, (usize, usize))> = Vec::new(); + for i in 0..self.boxes.len() { + for j in (i+1)..self.boxes.len() { + connections.push((self.boxes[i].dst(self.boxes[j]), (i, j))); + } + } + connections.sort_by(|a, b| a.0.cmp(&b.0)); + + let mut connections: Vec<(usize, usize)> = connections.into_iter() + .map(|(_, coord)| coord) + .collect(); + //connections.sort(); + + let mut circuits: Vec> = Vec::new(); + let mut it_connections = connections.iter(); + while let Some((b1, b2)) = it_connections.next() { + if let Some(i) = circuits.iter().position(|s| s.contains(b1)) { + if let Some(j) = circuits.iter().position(|s| s.contains(b2)) { + circuits.push( circuits[i].union(&circuits[j]).map(|v| *v).collect() ); + circuits.remove(i.max(j)); + if i != j { + circuits.remove(i.min(j)); + } + } else { + circuits[i].insert(*b2); + } + } else if let Some(i) = circuits.iter().position(|s| s.contains(b2)) { + if let Some(j) = circuits.iter().position(|s| s.contains(b1)) { + circuits.push( circuits[i].union(&circuits[j]).map(|v| *v).collect() ); + circuits.remove(i.max(j)); + if i != j { + circuits.remove(i.min(j)); + } + } else { + circuits[i].insert(*b1); + } + } else { + let mut s: HashSet = HashSet::new(); + s.insert(*b1); + s.insert(*b2); + circuits.push(s); + } + circuits.sort_by(|a, b| b.len().cmp(&a.len())); + if circuits[0].len() == self.boxes.len() { + return self.boxes[*b1].x * self.boxes[*b2].x; + } + } + panic!("No circuits with all junctions"); + } } pub fn run(input: &str) -> Result<(), Box> { let p = Puzzle::new(input); println!("part1: {}", p.part1(1000)); + println!("part2: {}", p.part2()); Ok(()) } @@ -132,6 +184,10 @@ mod tests { #[test] fn test_part1() { - assert_eq!(40, Puzzle::new(TEST_INPUT).part1(10)); + assert_eq!(Puzzle::new(TEST_INPUT).part1(10), 40); + } + #[test] + fn test_part2() { + assert_eq!(Puzzle::new(TEST_INPUT).part2(), 25272); } }