From: alex <> Date: Tue, 2 Dec 2025 15:10:53 +0000 (+0100) Subject: day02: part2 X-Git-Url: https://aoc.elinar.fr/?a=commitdiff_plain;h=8a093f0dd67753d86df5b9b8e11ac8cb38bbb7bf;p=aoc_2025 day02: part2 --- diff --git a/src/day02.rs b/src/day02.rs index cc55d4f..beee766 100644 --- a/src/day02.rs +++ b/src/day02.rs @@ -2,6 +2,7 @@ use std::error::Error; pub fn run(input: &str) -> Result<(), Box> { println!("part 1: {}", part1(input)?); + println!("part 2: {}", part2(input)?); Ok(()) } @@ -69,6 +70,43 @@ fn part1(input: &str) -> Result> { 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::>().windows(2).all(|w| w[0] == w[1]) { + return true; + } + j -= 1; + } + return false; +} + +fn part2(input: &str) -> Result> { + 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::().unwrap(); + let mut n = a.to_string(); + let mut nn = n.parse::().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()); + } }