use itertools::Itertools; use ndarray::prelude::*; use petgraph::prelude::*; use petgraph::visit::{IntoNodeReferences, Walker}; use std::collections::BinaryHeap; use std::fmt::{Display, Write}; use std::fs::File; use std::io::{BufRead, BufReader, Lines}; use std::str::FromStr; use std::time::Instant; // BOILERPLATE type InputIter = Lines>; fn get_input() -> InputIter { let f = File::open("input").unwrap(); let br = BufReader::new(f); br.lines() } fn main() { let start = Instant::now(); let ans1 = problem1(get_input()); let duration = start.elapsed(); println!("Problem 1 solution: {} [{}s]", ans1, duration.as_secs_f64()); let start = Instant::now(); let ans2 = problem2(get_input()); let duration = start.elapsed(); println!("Problem 2 solution: {} [{}s]", ans2, duration.as_secs_f64()); } // PARSE #[derive(Hash, PartialEq, Eq, Clone, Debug)] struct Coord { x: usize, y: usize, z: usize, } impl FromStr for Coord { type Err = Box; fn from_str(value: &str) -> Result { let (x, y, z) = value.split(',').next_tuple().unwrap(); Ok(Self { x: x.parse()?, y: y.parse()?, z: z.parse()?, }) } } #[derive(Clone, Hash, PartialEq, Eq)] struct BrickBlock { c1: Coord, c2: Coord, } impl std::fmt::Debug for BrickBlock { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { writeln!( f, "[{},{},{} - {},{},{}]", self.c1.x, self.c1.y, self.c1.z, self.c2.x, self.c2.y, self.c2.z ) } } impl BrickBlock { fn bottom_z_plane(&self) -> usize { std::cmp::min(self.c1.z, self.c2.z) } fn top_z_plane(&self) -> usize { std::cmp::max(self.c1.z, self.c2.z) } fn bottom_x_plane(&self) -> usize { std::cmp::min(self.c1.x, self.c2.x) } fn top_x_plane(&self) -> usize { std::cmp::max(self.c1.x, self.c2.x) } fn bottom_y_plane(&self) -> usize { std::cmp::min(self.c1.y, self.c2.y) } fn top_y_plane(&self) -> usize { std::cmp::max(self.c1.y, self.c2.y) } } impl From<&str> for BrickBlock { fn from(value: &str) -> Self { let (c1, c2) = value.split_once('~').unwrap(); Self { c1: c1.parse().unwrap(), c2: c2.parse().unwrap(), } } } impl PartialOrd for BrickBlock { fn partial_cmp(&self, other: &Self) -> Option { Some(other.bottom_z_plane().cmp(&self.bottom_z_plane())) } } // Note this is a reversed ordering impl Ord for BrickBlock { fn cmp(&self, other: &Self) -> std::cmp::Ordering { self.bottom_z_plane().cmp(&other.bottom_z_plane()) } } type BlockMap = Array3; type MapTile = Option; struct BlockPile { blocks: Vec, block_map: Array3, bounds: (usize, usize, usize), graph: Graph, } impl BlockPile { fn remove_block(&mut self, block: &BrickBlock) { // loop over the (inclusive) bounding coordinates and remove them all from the map self.block_map .slice_mut(s![ block.bottom_x_plane()..block.top_x_plane() + 1, block.bottom_y_plane()..block.top_y_plane() + 1, block.bottom_z_plane()..block.top_z_plane() + 1, ]) .fill(None); self.blocks.remove(self.blocks.iter().position(|b| b == block).unwrap()); } fn add_block(&mut self, block: &BrickBlock) { // loop over the (inclusive) bounding coordinates and remove them all from the map self.block_map .slice_mut(s![ block.bottom_x_plane()..block.top_x_plane() + 1, block.bottom_y_plane()..block.top_y_plane() + 1, block.bottom_z_plane()..block.top_z_plane() + 1, ]) .fill(Some(block.to_owned())); self.blocks.push(block.clone()); } fn blocks_directly_above(&self, block: &BrickBlock) -> Vec { // find the top plane of the block // get the array range of all squares at z_plane + 1 within the bounds of x & y // i think there is a built in way in ndarray to do this... let directly_above = self.block_map.slice(s![ block.bottom_x_plane()..block.top_x_plane() + 1, block.bottom_y_plane()..block.top_y_plane() + 1, block.top_z_plane() + 1..std::cmp::min(block.top_z_plane() + 2, self.bounds.2) ]); directly_above.iter().filter_map(|v| v.clone()).unique().collect() } fn supported_by(&self, block: &BrickBlock) -> usize { let z_plane = std::cmp::min(block.c1.z, block.c2.z); // get the slice of tiles below us let directly_below = self.block_map.slice(s![ block.bottom_x_plane()..block.top_x_plane() + 1, block.bottom_y_plane()..block.top_y_plane() + 1, z_plane - 1..z_plane // the layer below ]); directly_below.iter().filter_map(|v| v.clone()).unique().count() } fn blocks_above_will_move_if_we_are_gone(&mut self, block: &BrickBlock) -> bool { self.blocks_directly_above(&block) .iter() .map(|b| self.supported_by(b)) .any(|b| b == 1) // block we support will move if we are their only support } fn blocks_supported_by_at_all(&self, block: &BrickBlock) -> Vec { self.blocks_directly_above(&block).iter().map(|b| b.clone()).collect() } /// Find the plane of the first block directly below us fn supporting_plane(&self, block: &BrickBlock) -> Option { // find the bottom plane of ourselves let z_plane = std::cmp::min(block.c1.z, block.c2.z); // get the slice of tiles below us let directly_below = self.block_map.slice(s![ block.bottom_x_plane()..block.top_x_plane() + 1, block.bottom_y_plane()..block.top_y_plane() + 1, 1..z_plane // don't include our own plane ]); // find the highest top z value of those let block_below = directly_below .indexed_iter() .filter_map(|(idx, v)| if let Some(val) = v { Some((idx, val)) } else { None }) .max_by_key(|(_idx, v)| v.top_z_plane()); if let Some(block) = block_below { Some(block.1.top_z_plane()) } else { None } } fn drop_blocks(&mut self) { // VecDeque doesn't sort and Vec isn't convenient for pushback and popfront, so eh... use a heap. let mut blocks_to_move = BinaryHeap::from(self.blocks.clone()); while let Some(mut block) = blocks_to_move.pop() { let z_move = match self.supporting_plane(&block) { Some(z) if z + 1 != block.bottom_z_plane() => block.bottom_z_plane() - (z + 1), None if block.bottom_z_plane() != 1 => block.bottom_z_plane() - 1, _ => { continue; } // we are in position already with nothing below us }; self.remove_block(&block); block.c1.z -= z_move; block.c2.z -= z_move; self.add_block(&block); blocks_to_move.push(block); } } fn build_graph(&mut self) { self.blocks.sort_by_key(|b| b.bottom_z_plane()); for b in 0..self.blocks.len() { self.graph.add_node(self.blocks[b].clone()); } for b in 0..self.blocks.len() { let block = &self.blocks[b]; let depends_on_us = self.blocks_supported_by_at_all(block); for dependent in depends_on_us { self.graph.add_edge( b.into(), self.blocks.iter().position(|b| b == &dependent).unwrap().into(), (), ); } } } } impl From> for BlockPile { fn from(lines: Lines) -> Self { let blocks = lines.map(|line| BrickBlock::from(line.unwrap().as_str())).collect_vec(); let mut bounds = (0, 0, 0); for block in &blocks { bounds.0 = std::cmp::max(block.top_x_plane() + 1, bounds.0); bounds.1 = std::cmp::max(block.top_y_plane() + 1, bounds.1); bounds.2 = std::cmp::max(block.top_z_plane() + 1, bounds.2); } let mut new = BlockPile { blocks: Vec::new(), bounds, block_map: BlockMap::from_elem(bounds, None), graph: Graph::default(), }; for block in blocks { new.add_block(&block); } new } } impl Display for BlockPile { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { for z in (0..self.bounds.2).rev() { let z_plane = self.block_map.slice(s![.., .., z..z+1]); if z_plane.iter().all(|b| b.is_none()) { continue }; for i in 0..self.bounds.0 { // XZ view let y = z_plane.slice(s![i..i + 1, .., ..]); f.write_char( match y.iter().enumerate().find_map(|(idx, val)| val.is_some().then(|| idx)) { None => ' ', Some(0) | Some(1) => '█', Some(2) | Some(3) => '▓', Some(4) | Some(5) => '▒', Some(6) | Some(7) => '░', _ => '░', }, )?; } write!(f, " {} ", z)?; for y in 0..self.bounds.1 { let x = z_plane.slice(s![.., y..y + 1, ..]); f.write_char( match x.iter().enumerate().find_map(|(idx, val)| val.is_some().then(|| idx)) { None => ' ', Some(0) | Some(1) => '█', Some(2) | Some(3) => '▓', Some(4) | Some(5) => '▒', Some(6) | Some(7) => '░', _ => '░', }, )?; } writeln!(f, " {}", z)?; } Ok(()) } } // PROBLEM 1 solution fn problem1(input: Lines) -> u64 { let mut pile = BlockPile::from(input); println!("{}", pile); println!("dropping blocks!"); pile.drop_blocks(); println!("{}", pile); let blocks = pile.blocks.clone(); let removable: Vec<_> = blocks .iter() .filter(|b| !pile.blocks_above_will_move_if_we_are_gone(*b)) .collect(); removable.len() as u64 } // PROBLEM 2 solution fn problem2(input: Lines) -> u64 { let mut pile = BlockPile::from(input); pile.drop_blocks(); pile.build_graph(); println!("{}", pile); let mut accum = 0; let fixed_nodes = pile .graph .node_references() .filter(|(_idx, b)| b.bottom_z_plane() == 1) .map(|(idx, _b)| idx) .collect_vec(); for node in pile.graph.node_indices() { // remove links to node's neighbors let dependents = pile.graph.neighbors(node).collect_vec(); let edges = pile.graph.edges(node).map(|v| v.id()).collect_vec(); for edge in edges { pile.graph.remove_edge(edge); } // find how many nodes are reachable from z = 1 - these won't move let safe_blocks = fixed_nodes .iter() .flat_map(|origin| { Bfs::new(&pile.graph, *origin) .iter(&pile.graph) .map(|n| pile.graph[n].clone()) }) .unique() .count(); // we are looking for the nodes that *will* disintegrate accum += pile.graph.node_count() - safe_blocks; // put the graph back how it was for neigh in dependents { pile.graph.add_edge(node, neigh, ()); } } accum as u64 } #[cfg(test)] mod tests { use crate::*; use std::io::Cursor; const EXAMPLE: &str = &"1,0,1~1,2,1 0,0,2~2,0,2 0,2,3~2,2,3 0,0,4~0,2,4 2,0,5~2,2,5 0,1,6~2,1,6 1,1,8~1,1,9"; #[test] fn problem1_example() { let c = Cursor::new(EXAMPLE); assert_eq!(problem1(c.lines()), 5); } #[test] fn problem2_example() { let c = Cursor::new(EXAMPLE); assert_eq!(problem2(c.lines()), 7); } }