use regex::Regex; const INPUT_FILE: &str = "input"; fn p1(input: &str) { let re = Regex::new(r"mul\(([0-9]{1,3}),([0-9]{1,3})\)").unwrap(); let mut result: u32 = 0; for (_, [x, y]) in re.captures_iter(input).map(|m| m.extract()) { result += x.parse::().unwrap() * y.parse::().unwrap(); } println!("Result: {}", result); } fn p2(input: &str) { let re = Regex::new(r"do\(\)|don't\(\)|mul\(([0-9]{1,3}),([0-9]{1,3})\)").unwrap(); let mut doing = true; let mut result: u32 = 0; for m in re.captures_iter(input) { let mut it = m.iter(); match it.next().unwrap().map(|m| m.as_str()) { Some("do()") => doing = true, Some("don't()") => doing = false, Some(mul) if doing && mul.starts_with("mul") => { if let [x, y] = it .flatten() .map(|m| m.as_str().parse::().unwrap()) .collect::>()[..] { result += x * y; } } _ => (), } } println!("Result: {}", result); } fn main() { let input = std::fs::read_to_string(INPUT_FILE).unwrap(); p1(&input); p2(&input); }