|
| 1 | +use std::collections::BTreeSet; |
| 2 | + |
| 3 | +use aoc_utils::*; |
| 4 | +use itertools::Itertools; |
| 5 | + |
| 6 | +advent_of_code::solution!(4); |
| 7 | + |
| 8 | +pub fn part_one(input: &str) -> Option<u64> { |
| 9 | + let map = input.c_map(); |
| 10 | + let num = map |
| 11 | + .iter() |
| 12 | + .enumerate() |
| 13 | + .flat_map(|(x, v)| { |
| 14 | + v.iter() |
| 15 | + .enumerate() |
| 16 | + .filter(|(_, c)| **c == '@') |
| 17 | + .map(|(y, _)| Point(x, y)) |
| 18 | + .collect_vec() |
| 19 | + }) |
| 20 | + .filter(|p| { |
| 21 | + DirExt::neighbors(*p, Bounds(map.len() - 1, map[0].len() - 1)) |
| 22 | + .iter() |
| 23 | + .filter(|p2| map[p2.0][p2.1] == '@') |
| 24 | + .count() |
| 25 | + < 4 |
| 26 | + }) |
| 27 | + .count(); |
| 28 | + Some(num as u64) |
| 29 | +} |
| 30 | + |
| 31 | +pub fn part_two(input: &str) -> Option<u64> { |
| 32 | + let mut map = input.c_map(); |
| 33 | + let mut queue = map |
| 34 | + .iter() |
| 35 | + .enumerate() |
| 36 | + .flat_map(|(x, v)| { |
| 37 | + v.iter() |
| 38 | + .enumerate() |
| 39 | + .filter(|(_, c)| **c == '@') |
| 40 | + .map(|(y, _)| Point(x, y)) |
| 41 | + .collect_vec() |
| 42 | + }) |
| 43 | + .collect::<BTreeSet<Point>>(); |
| 44 | + let mut removed = 0; |
| 45 | + while !queue.is_empty() { |
| 46 | + let curr = queue.pop_first().unwrap(); |
| 47 | + let neighbors = DirExt::neighbors(curr, Bounds(map.len() - 1, map[0].len() - 1)); |
| 48 | + if neighbors.iter().filter(|p| map[p.0][p.1] == '@').count() < 4 { |
| 49 | + removed += 1; |
| 50 | + map[curr.0][curr.1] = '.'; |
| 51 | + neighbors |
| 52 | + .into_iter() |
| 53 | + .filter(|p| map[p.0][p.1] == '@') |
| 54 | + .for_each(|p| { |
| 55 | + queue.insert(p); |
| 56 | + }); |
| 57 | + } |
| 58 | + } |
| 59 | + Some(removed) |
| 60 | +} |
| 61 | + |
| 62 | +#[cfg(test)] |
| 63 | +mod tests { |
| 64 | + use super::*; |
| 65 | + |
| 66 | + #[test] |
| 67 | + fn test_part_one() { |
| 68 | + let result = part_one(&advent_of_code::template::read_file("examples", DAY)); |
| 69 | + assert_eq!(result, Some(13)); |
| 70 | + } |
| 71 | + |
| 72 | + #[test] |
| 73 | + fn test_part_two() { |
| 74 | + let result = part_two(&advent_of_code::template::read_file("examples", DAY)); |
| 75 | + assert_eq!(result, Some(43)); |
| 76 | + } |
| 77 | +} |
0 commit comments