|
| 1 | +use anyhow::Result; |
| 2 | +use ndarray::Array2; |
| 3 | + |
| 4 | +fn neighbour_coords(y: usize, x: usize) -> [(usize, usize); 8] { |
| 5 | + [ |
| 6 | + (y.wrapping_sub(1), x.wrapping_sub(1)), |
| 7 | + (y.wrapping_sub(1), x), |
| 8 | + (y.wrapping_sub(1), x.wrapping_add(1)), |
| 9 | + (y, x.wrapping_sub(1)), |
| 10 | + (y, x.wrapping_add(1)), |
| 11 | + (y.wrapping_add(1), x.wrapping_sub(1)), |
| 12 | + (y.wrapping_add(1), x), |
| 13 | + (y.wrapping_add(1), x.wrapping_add(1)), |
| 14 | + ] |
| 15 | +} |
| 16 | + |
| 17 | +fn neighbours(grid: &Array2<bool>, y: usize, x: usize) -> usize { |
| 18 | + neighbour_coords(y, x) |
| 19 | + .into_iter() |
| 20 | + .filter(|&(y, x)| *grid.get((y, x)).unwrap_or(&false)) |
| 21 | + .count() |
| 22 | +} |
| 23 | + |
| 24 | +fn calculate(mut grid: Array2<bool>) -> (u32, u32) { |
| 25 | + let mut p1 = 0; |
| 26 | + let mut p2 = 0; |
| 27 | + let mut changed_q = Vec::with_capacity(2048); |
| 28 | + |
| 29 | + for y in 0..grid.dim().0 { |
| 30 | + for x in 0..grid.dim().1 { |
| 31 | + if *grid.get((y, x)).expect("indexes are valid") && neighbours(&grid, y, x) < 4 { |
| 32 | + p1 += 1; |
| 33 | + changed_q.push((y, x)); |
| 34 | + } |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + while let Some((y, x)) = changed_q.pop() { |
| 39 | + { |
| 40 | + let itm = grid.get_mut((y, x)).expect("indexes are valid"); |
| 41 | + if !*itm { |
| 42 | + continue; |
| 43 | + } |
| 44 | + *itm = false |
| 45 | + } |
| 46 | + p2 += 1; |
| 47 | + |
| 48 | + neighbour_coords(y, x) |
| 49 | + .into_iter() |
| 50 | + .filter(|(y, x)| *grid.get((*y, *x)).unwrap_or(&false) && neighbours(&grid, *y, *x) < 4) |
| 51 | + .for_each(|(y, x)| changed_q.push((y, x))); |
| 52 | + } |
| 53 | + |
| 54 | + (p1, p2) |
| 55 | +} |
| 56 | + |
| 57 | +pub fn run_2025_04(inp: &str) -> Result<String> { |
| 58 | + let grid = crate::grid_util::make_bool_grid::<b'@'>(inp)?; |
| 59 | + let (p1, p2) = calculate(grid); |
| 60 | + Ok(format!("{p1}\n{p2}")) |
| 61 | +} |
| 62 | + |
| 63 | +#[cfg(test)] |
| 64 | +mod tests { |
| 65 | + use super::*; |
| 66 | + |
| 67 | + const EXAMPLE_DATA: &str = include_str!("../inputs/examples/2025_04"); |
| 68 | + const REAL_DATA: &str = include_str!("../inputs/real/2025_04"); |
| 69 | + |
| 70 | + #[test] |
| 71 | + fn test_example() { |
| 72 | + let grid = crate::grid_util::make_bool_grid::<b'@'>(EXAMPLE_DATA).unwrap(); |
| 73 | + assert_eq!(calculate(grid), (13, 43)); |
| 74 | + } |
| 75 | + |
| 76 | + #[test] |
| 77 | + fn test_real() { |
| 78 | + let grid = crate::grid_util::make_bool_grid::<b'@'>(REAL_DATA).unwrap(); |
| 79 | + assert_eq!(calculate(grid), (1349, 8277)); |
| 80 | + } |
| 81 | +} |
0 commit comments