use regex::Regex; static DAY: u8 = 3; fn main() { let input = advent::read_lines(DAY); println!("{DAY}a: {}", sum_multiplications(&input, true)); println!("{DAY}b: {}", sum_multiplications(&input, false)); } fn sum_multiplications(input: &[String], ignore_do: bool) -> u32 { let re = Regex::new(r"(do)\(\)|(don't)\(\)|(mul)\(([0-9]{1,3}),([0-9]{1,3})\)").unwrap(); let mut sum = 0; let mut muls_enabled = true; for line in input { for cap in re.captures_iter(line) { if cap.get(1).is_some() { // do muls_enabled = true; } else if cap.get(2).is_some() { // don't muls_enabled = false; } else if cap.get(3).is_some() { // mul if ignore_do || muls_enabled { let f1 = cap[4].parse::().unwrap(); let f2 = cap[5].parse::().unwrap(); sum += f1 * f2; } } } } sum } #[cfg(test)] mod tests { use super::*; #[test] fn test() { let input = [ "xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5))" ].iter().map(|&x| String::from(x)).collect::>(); assert_eq!(sum_multiplications(&input, true), 161); let input = [ "xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5))" ].iter().map(|&x| String::from(x)).collect::>(); assert_eq!(sum_multiplications(&input, false), 48); } }