]> aoc.elinar.fr Git - aoc_2025/commitdiff
day04: part2
authoralex <>
Fri, 5 Dec 2025 11:14:36 +0000 (12:14 +0100)
committeralex <>
Fri, 5 Dec 2025 11:14:36 +0000 (12:14 +0100)
src/day04.rs

index 42690e9ac3f65dc3ed75718ce775de56a35a68c1..ebd68ce453ce3e15e284d18d4e7320ee6541d386 100644 (file)
@@ -3,6 +3,7 @@ use std::collections::HashMap;
 
 struct Puzzle {
     map: HashMap<(i32, i32), char>,
+    rolls: usize,
 }
 
 impl Puzzle {
@@ -16,25 +17,43 @@ impl Puzzle {
                     .filter(|(_, c)| *c == '@')
                     .for_each(|(j, c)| { map.insert((i as i32, j as i32), c); });
             });
-        Puzzle { map: map }
+        Puzzle { map: map, rolls: 0 }
     }
 
-    fn part1(&self) -> usize {
-        self.map.iter().filter(|((i,j), _)| {
+    fn count_and_remove(&mut self) -> usize {
+        let mut rolls: Vec<(i32, i32)> = Vec::new();
+        let c = self.map.iter().filter(|((i,j), _)| {
             let c = [(-1,-1), (-1,0), (-1,1), (0,-1), (0,1), (1,-1), (1,0), (1,1)].into_iter()
                 .filter(|(dx,dy)| self.map.contains_key(&(i+dx, j+dy)))
                 .count();
-            //println!("  (i,j): {} {} - {}", i, j, c);
-            //println!("{}, {}", i, j);
             c < 4
         })
-        .count()
+        .map(|(key, _)| {
+            rolls.push(*key);
+            1
+        })
+        .count();
+        rolls.into_iter().for_each(|key| { self.map.remove(&key); });
+        self.rolls += c;
+        c
+    }
+    fn part1(&mut self) -> usize {
+        self.count_and_remove()
+    }
+
+    fn part2(&mut self) -> usize {
+        let mut c = self.count_and_remove();
+        while c > 0 {
+            c = self.count_and_remove();
+        }
+        self.rolls
     }
 }
 
 pub fn run(input: &str) -> Result<(), Box<dyn Error>> {
-    let p = Puzzle::new(input);
+    let mut p = Puzzle::new(input);
     println!("part1: {}", p.part1());
+    println!("part2: {}", p.part2());
     Ok(())
 }
 
@@ -57,6 +76,10 @@ mod tests {
 
     #[test]
     fn test_part1() {
-        assert_eq!(Puzzle::new(INPUT).part1(), 13);
+        assert_eq!(13, Puzzle::new(INPUT).part1());
+    }
+    #[test]
+    fn test_part2() {
+        assert_eq!(43, Puzzle::new(INPUT).part2());
     }
 }