Today's task was easy for me, though as usual I had to relearn a few things after almost a year without coding, such as how to capture patterns with regular expressions.
I admit it would be a lot harder if one did the full parsing oneself, which on the other hand would be cool. It is a good excuse to relearn combinatorial parsing.
This is my code for today.
Task 1:
use regex::Regex;
use std::fs::read_to_string;
fn main() {
let s = read_to_string("input.txt").unwrap();
let re = Regex::new(r"mul\((\d+),(\d+)\)").unwrap();
let prod: Vec<(u32, u32)>;
prod = re
.captures_iter(&s)
.map(|caps| {
let (_, [m1, m2]) = caps.extract();
(m1.parse::<u32>().unwrap(), m2.parse::<u32>().unwrap())
})
.collect();
let r = prod.iter().fold(0, |acc, (m1, m2)| acc + (m1 * m2));
println!("{}", r);
}
And task 2, for which I was going to write a full regexp then went lazy and used the split method:
use regex::Regex;
use std::fs::read_to_string;
fn main() {
let s = read_to_string("input.txt").unwrap();
let re = Regex::new(r"mul\((\d+),(\d+)\)").unwrap();
let mut prod: Vec<(u32, u32)> = Vec::new();
let s = s.split("do()");
for i in s {
if let Some(i) = i.split("don't()").next() {
prod.extend(
re.captures_iter(i)
.map(|caps| {
let (_, [m1, m2]) = caps.extract();
(m1.parse::<u32>().unwrap(), m2.parse::<u32>().unwrap())
})
.collect::<Vec<(u32, u32)>>(),
);
}
}
let r = prod.iter().fold(0, |acc, (m1, m2)| acc + (m1 * m2));
println!("{}", r);
}
#
aoc24