Advent of Code 2024 Day 3 - Rust
Part One
I solved day three mostly thanks to regex. For the first part the line:
let matcher = Regex::new(r#"mul\(([0-9]+),([0-9]+)\)"#).unwrap();
was matched on the lines in the input. When a match occurred, the capture groups were parsed, multiplied and added to the total. The rules were pretty strict about it being an exact match, so there wasn't any need to compensate for things like whitespace.
Part Two
Given I had done part one with regex, I continued that into part two. I added a second regex to match one of the three valid commands.
let parent =
Regex::new(r#"(?<do>do\(\))|(?<mul>mul\([0-9]+,[0-9]+\))|(?<dont>don't\(\))"#).unwrap();
Then, based on which one matched, I set a boolean for whether to include or ignore the mul statements.
for line in content.lines() {
let _ = parent.captures_iter(line).for_each(|caps| {
if let Some(_) = caps.name("do") {
on = true;
} else if let Some(_) = caps.name("dont") {
on = false
} else if let Some(x) = caps.name("mul") {
if on {
let cap = matcher.captures(x.as_str()).unwrap();
let (_, [a, b]) = cap.extract();
let ai: i32 = a.parse().unwrap();
let bi: i32 = b.parse().unwrap();
total += ai * bi;
}
}
});
}
There was probably a way to avoid needing two regex statements, but combining them felt like overkill.
The complete solution can be found here.