From 927e5adad269c191913487d89cc033f7423fe0ca Mon Sep 17 00:00:00 2001 From: Greg Burri Date: Tue, 3 Dec 2024 18:42:02 +0100 Subject: [PATCH] Day 03 --- src/day03.rs | 68 ++++++++++++++++++++++++++++++++++++++++++++++++++++ src/days.rs | 10 ++++++++ src/main.rs | 4 ++-- 3 files changed, 80 insertions(+), 2 deletions(-) create mode 100644 src/day03.rs diff --git a/src/day03.rs b/src/day03.rs new file mode 100644 index 0000000..9be94ea --- /dev/null +++ b/src/day03.rs @@ -0,0 +1,68 @@ +use std::io::BufRead; + +use regex::Regex; + +pub fn read_program(mut reader: R) -> String +where + R: BufRead, +{ + let mut output = String::new(); + reader.read_to_string(&mut output).unwrap(); + output +} + +pub fn execute_corrupted_program(prog: &str) -> i32 { + let mul_re = Regex::new(r#"mul\((\d{1,3}),(\d{1,3})\)"#).unwrap(); + + let mut val = 0; + for cap in mul_re.captures_iter(prog) { + let n1 = cap[1].parse::().unwrap(); + let n2 = cap[2].parse::().unwrap(); + val += n1 * n2 + } + + val +} + +pub fn execute_corrupted_program_dodont(prog: &str) -> i32 { + let mul_re = Regex::new(r#"mul\((\d{1,3}),(\d{1,3})\)|don't\(\)|do\(\)"#).unwrap(); + + let mut val = 0; + let mut enable = true; + for cap in mul_re.captures_iter(prog) { + match &cap[0] { + "don't()" => enable = false, + "do()" => enable = true, + _ if enable => { + let n1 = cap[1].parse::().unwrap(); + let n2 = cap[2].parse::().unwrap(); + val += n1 * n2 + } + _ => (), // Skip 'mul' instruction. + } + } + val +} + +#[cfg(test)] +mod tests { + use super::*; + + static CORRUPTED_PROGRAM_PART1: &str = + r#"xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5))"#; + + #[test] + fn test_part1() { + let v = execute_corrupted_program(CORRUPTED_PROGRAM_PART1); + assert_eq!(v, 161); + } + + static CORRUPTED_PROGRAM_PART2: &str = + r#"xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5))"#; + + #[test] + fn test_part2() { + let v = execute_corrupted_program_dodont(CORRUPTED_PROGRAM_PART2); + assert_eq!(v, 48); + } +} diff --git a/src/days.rs b/src/days.rs index 03e4e34..1424849 100644 --- a/src/days.rs +++ b/src/days.rs @@ -21,3 +21,13 @@ pub fn day02() -> String { day02::nb_of_safe_reports_with_tolerance(&reports) ) } + +pub fn day03() -> String { + let f = fs::File::open("data/day03.input").unwrap(); + let program = day03::read_program(BufReader::new(f)); + format!( + "part1: {}, part2: {}", + day03::execute_corrupted_program(&program), + day03::execute_corrupted_program_dodont(&program) + ) +} diff --git a/src/main.rs b/src/main.rs index 15bf0ef..51cf7ce 100644 --- a/src/main.rs +++ b/src/main.rs @@ -5,7 +5,7 @@ use rayon::prelude::*; mod day01; mod day02; -// mod day03; +mod day03; // mod day04; // mod day05; // mod day06; @@ -45,7 +45,7 @@ fn main() { let days: Vec String> = vec![ days::day01, days::day02, - // days::day03, + days::day03, // days::day04, // days::day05, // days::day06, -- 2.45.2