From 5054b1b4986a4f82a9d6843140566b12947d37c5 Mon Sep 17 00:00:00 2001 From: Andrew Coleman Date: Wed, 21 Feb 2024 14:07:57 -0500 Subject: [PATCH] day 22 part 2 solution --- 2023/src/bin/22.rs | 54 +++++++++++++++++++++++++++++++++++----------- 1 file changed, 42 insertions(+), 12 deletions(-) diff --git a/2023/src/bin/22.rs b/2023/src/bin/22.rs index 6fc936e..7d83aa7 100644 --- a/2023/src/bin/22.rs +++ b/2023/src/bin/22.rs @@ -1,7 +1,7 @@ advent_of_code::solution!(22); use aoc_parse::{parser, prelude::*}; -use std::collections::{HashMap, HashSet}; +use std::collections::{HashMap, HashSet, VecDeque}; #[derive(Clone, Copy, Debug, PartialOrd, Ord, Eq, PartialEq)] struct Coord { @@ -26,12 +26,10 @@ impl Block { } fn below(&self, other: &Self) -> bool { - // self.id != other.id && self.intersect_xy(other) && self.two.z == other.one.z - 1 self.intersect_xy(other) && self.two.z == other.one.z - 1 } fn above(&self, other: &Self) -> bool { - // self.id != other.id && self.intersect_xy(other) && self.one.z == other.two.z + 1 self.intersect_xy(other) && self.one.z == other.two.z + 1 } } @@ -77,13 +75,6 @@ fn drop_blocks(blocks: &[Block]) -> Vec { btm } -fn pyprint(b: &Block) { - println!( - "(({}, {}, {}), ({}, {}, {}))", - b.one.x, b.one.y, b.one.z, b.two.x, b.two.y, b.two.z - ); -} - pub fn part_one(input_str: &str) -> Option { let input = parse(input_str); let btm = drop_blocks(&input); @@ -111,7 +102,46 @@ pub fn part_one(input_str: &str) -> Option { } pub fn part_two(input_str: &str) -> Option { - None + let input = parse(input_str); + let btm = drop_blocks(&input); + let mut a: HashMap> = HashMap::new(); + for outside in btm.iter() { + let mut above: Vec = vec![]; + for inside in btm.iter() { + if inside.above(&outside) { + above.push(inside.id); + } + } + a.insert(outside.id, above); + } + let mut result = 0; + let mut v: HashSet = HashSet::new(); + let mut p: VecDeque = VecDeque::new(); + for b in btm.iter() { + if b.one.z == 1 { + v.insert(b.id); + p.push_back(b.id); + } + } + for id in 1..=btm.len() { + let mut visited = v.clone(); + let mut path = p.clone(); + while let Some(next) = path.pop_front() { + if next == id { + continue; + } + if let Some(above) = a.get(&next) { + for &above_id in above { + if !visited.contains(&above_id) { + visited.insert(above_id); + path.push_back(above_id); + } + } + } + } + result += btm.len() - visited.len(); + } + Some(result) } #[cfg(test)] @@ -127,7 +157,7 @@ mod tests { #[test] fn test_part_two() { let result = part_two(&advent_of_code::template::read_file("examples", DAY)); - assert_eq!(result, None); + assert_eq!(result, Some(7)); } fn perform_test_intersect(