]> aoc.elinar.fr Git - aoc_2025/commitdiff
day02: part2
authoralex <>
Tue, 2 Dec 2025 15:10:53 +0000 (16:10 +0100)
committeralex <>
Tue, 2 Dec 2025 15:10:53 +0000 (16:10 +0100)
src/day02.rs

index cc55d4fe520460eb11490a1549a92c8726c608ba..beee76655fe32b939b4e589f79a97945175a7bf8 100644 (file)
@@ -2,6 +2,7 @@ use std::error::Error;
 
 pub fn run(input: &str) -> Result<(), Box<dyn Error>> {
     println!("part 1: {}", part1(input)?);
+    println!("part 2: {}", part2(input)?);
     Ok(())
 }
 
@@ -69,6 +70,43 @@ fn part1(input: &str) -> Result<u64, Box<dyn Error>> {
     Ok(res)
 }
 
+fn is_invalid_2(s: &str) -> bool {
+    if s.len() == 1 {
+        return false;
+    }
+    let mut j = s.len() / 2;
+    while j > 0 {
+        if s.as_bytes().chunks(j).collect::<Vec<_>>().windows(2).all(|w| w[0] == w[1]) {
+            return true;
+        }
+        j -= 1;
+    }
+    return false;
+}
+
+fn part2(input: &str) -> Result<u64, Box<dyn Error>> {
+    let mut res: u64 = 0;
+    input.trim_end_matches("\n").split(',')
+        .map(|ranges| ranges.split_once('-').unwrap())
+        // keep only the ranges with an even number of digits
+        // => filter out when a and b have the same odd number of digits
+        .for_each(|(a, b)| {
+            //println!("{} → {}", a, b);
+            let bn = b.parse::<u64>().unwrap();
+            let mut n = a.to_string();
+            let mut nn = n.parse::<u64>().unwrap();
+            while nn <= bn {
+                if is_invalid_2(&n) {
+                    //println!("   invalid: {}", n);
+                    res += nn;
+                }
+                nn += 1;
+                n = nn.to_string();
+            }
+        });
+    Ok(res)
+}
+
 #[cfg(test)]
 mod tests {
     use super::*;
@@ -104,4 +142,23 @@ mod tests {
     fn test_part1() {
         assert_eq!(1227775554, part1(INPUT).unwrap());
     }
+
+    #[test]
+    fn test_is_invalid_2() {
+        assert_eq!(is_invalid_2("11"), true);
+        assert_eq!(is_invalid_2("22"), true);
+        assert_eq!(is_invalid_2("55"), true);
+        assert_eq!(is_invalid_2("66"), true);
+        assert_eq!(is_invalid_2("111"), true);
+        assert_eq!(is_invalid_2("2323"), true);
+        assert_eq!(is_invalid_2("447447"), true);
+        assert_eq!(is_invalid_2("566566"), true);
+        assert_eq!(is_invalid_2("2121212121"), true);
+        assert_eq!(is_invalid_2("2121221212"), true);
+        assert_eq!(is_invalid_2("824824824"), true);
+    }
+    #[test]
+    fn test_part2() {
+        assert_eq!(4174379265, part2(INPUT).unwrap());
+    }
 }