This commit is contained in:
traxys 2024-12-03 13:46:29 +01:00
parent 8360196d0f
commit 8f6f15c473
3 changed files with 108 additions and 0 deletions

74
src/bin/day3.rs Normal file
View file

@ -0,0 +1,74 @@
use std::time::Instant;
use aoc_2024::{load, print_res};
use bstr::BString;
use regex::Regex;
type Parsed<'a> = &'a str;
pub fn parsing(input: &BString) -> color_eyre::Result<Parsed> {
core::str::from_utf8(input).map_err(Into::into)
}
pub fn part1(input: Parsed) {
let regex = Regex::new(r#"mul\((\d+),(\d+)\)"#).unwrap();
let mut total = 0;
for capture in regex.captures_iter(input) {
let first: u64 = capture.get(1).unwrap().as_str().parse().unwrap();
let second: u64 = capture.get(2).unwrap().as_str().parse().unwrap();
total += first * second;
}
print_res!("Sum of multiplications: {total}");
}
pub fn part2(input: Parsed) {
let regex = Regex::new(r#"don't\(\)|do\(\)|mul\((\d+),(\d+)\)"#).unwrap();
let mut total = 0;
let mut enabled = true;
for capture in regex.captures_iter(input) {
let instr = capture.get(0).unwrap().as_str();
match instr {
"do()" => enabled = true,
"don't()" => enabled = false,
// `mul(a,b)`
_ => {
if !enabled {
continue;
}
let first: u64 = capture.get(1).unwrap().as_str().parse().unwrap();
let second: u64 = capture.get(2).unwrap().as_str().parse().unwrap();
total += first * second;
}
}
}
print_res!("Sum of multiplications: {total}");
}
pub fn main() -> color_eyre::Result<()> {
let context = load()?;
let start = Instant::now();
let parsed = parsing(&context.input)?;
let elapsed = humantime::format_duration(start.elapsed());
let start = Instant::now();
if context.part == 1 {
part1(parsed);
} else {
part2(parsed);
}
let elapsed_part = humantime::format_duration(start.elapsed());
println!(" Parsing: {elapsed}");
println!(" Solving: {elapsed_part}");
Ok(())
}