pub fn run(input: &str) -> Result<(), Box<dyn Error>> {
println!("part 1: {}", part1(input)?);
+ println!("part 2: {}", part2(input)?);
Ok(())
}
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::*;
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());
+ }
}