diff --git a/y2024/src/days/d3.rs b/y2024/src/days/d3.rs index a02adbf..b1c00d4 100644 --- a/y2024/src/days/d3.rs +++ b/y2024/src/days/d3.rs @@ -26,56 +26,26 @@ fn extract_mul_pairs(line: &str) -> Vec<(i32, i32)> { } fn extract_mul_pairs_dont(line: &str) -> Vec<(i32, i32)> { - let mut pairs = Vec::new(); - for (idx, _) in line.match_indices("mul(") { - if let Some(dont_func) = line[..idx].rfind("don't()") { - if let Some(do_func) = line[..idx].rfind("do()") { - if do_func < dont_func { - continue; - } + let reg = Regex::new(r"(mul\([0-9]{1,3},[0-9]{1,3}\))|(don't\(\)|do\(\))").unwrap(); + let mut enabled = true; + reg.find_iter(line) + .map(|m| { + let match_str = m.as_str(); + if match_str == "don't()" { + enabled = false; + } else if match_str == "do()" { + enabled = true; + } + if !["don't()", "do()"].contains(&match_str) && enabled { + let (a, b) = match_str[4..match_str.len() - 1].split_once(",").unwrap(); + let a = a.parse::().unwrap(); + let b = b.parse::().unwrap(); + (a, b) } else { - continue; + (0, 0) } - } - let mut invalid = false; - let mut comma_pos = 0; - let mut pair = ("".to_string(), "".to_string()); - // max length of parenthesis == 9 - for paren_idx in 0..9 { - let paren_content = match line.as_bytes().get(idx + 4 + paren_idx) { - Some(content) => *content as char, - None => { - invalid = true; - break; - } - }; - if paren_content == ')' { - if comma_pos == 0 { - invalid = true; - } - break; - } - if paren_content == ',' { - comma_pos = paren_idx; - continue; - } - if !paren_content.is_ascii_digit() { - invalid = true; - break; - } - if comma_pos == 0 { - pair.0.push(paren_content); - } else { - pair.1.push(paren_content); - } - } - if !invalid { - let a = pair.0.parse::().unwrap(); - let b = pair.1.parse::().unwrap(); - pairs.push((a, b)); - } - } - pairs + }) + .collect::>() } pub fn process_part2(input: &str) -> i32 {