From 8e9c34571de5df45f70319106513a10bc639a350 Mon Sep 17 00:00:00 2001 From: Felix Suchert Date: Sun, 15 Dec 2024 23:33:21 +0100 Subject: [PATCH] Add parser for don't --- src/solutions/day_3.rs | 65 +++++++++++++++++++++++++++++++++++++++--- 1 file changed, 61 insertions(+), 4 deletions(-) diff --git a/src/solutions/day_3.rs b/src/solutions/day_3.rs index d1bd143..a89920b 100644 --- a/src/solutions/day_3.rs +++ b/src/solutions/day_3.rs @@ -10,6 +10,12 @@ enum ParserState { ExpectLParen, ReadNum1, ReadNum2, + ExpectO, + ExpectNorLParen, + ExpectApostrophe, + ExpectT, + ExpectDontLParen, + ExpectRParen(bool), } pub fn run(mut args: env::Args) -> std::io::Result<()> { @@ -20,10 +26,13 @@ pub fn run(mut args: env::Args) -> std::io::Result<()> { let f = File::open(filename)?; let reader = BufReader::new(f); - let mut sum = 0; + let mut sum_a = 0; + let mut sum_b = 0; let mut num_buf = String::with_capacity(3); let mut a = 0; + let mut mul_enabled = true; + for line in reader.lines() { let l = line.unwrap(); if l.is_empty() { @@ -37,6 +46,8 @@ pub fn run(mut args: env::Args) -> std::io::Result<()> { ParserState::Search => { if c == 'm' { ParserState::ExpectU + } else if c == 'd' { + ParserState::ExpectO } else { ParserState::Search } @@ -86,7 +97,10 @@ pub fn run(mut args: env::Args) -> std::io::Result<()> { if c == ')' && !num_buf.is_empty() { // parse the number, assign to b, set to ParserState::ReadNum2 let b = u32::from_str(&num_buf).unwrap(); - sum += a * b; + sum_a += a * b; + if mul_enabled { + sum_b += a * b; + } } // teardown in any case @@ -95,15 +109,58 @@ pub fn run(mut args: env::Args) -> std::io::Result<()> { ParserState::Search } } + ParserState::ExpectO => { + if c == 'o' { + ParserState::ExpectNorLParen + } else { + ParserState::Search + } + } + ParserState::ExpectNorLParen => { + if c == '(' { + ParserState::ExpectRParen(true) + } else if c == 'n' { + ParserState::ExpectApostrophe + } else { + ParserState::Search + } + } + ParserState::ExpectApostrophe => { + if c == '\'' { + ParserState::ExpectT + } else { + ParserState::Search + } + } + ParserState::ExpectT => { + if c == 't' { + ParserState::ExpectDontLParen + } else { + ParserState::Search + } + } + ParserState::ExpectDontLParen => { + if c == '(' { + ParserState::ExpectRParen(false) + } else { + ParserState::Search + } + } + ParserState::ExpectRParen(enable) => { + if c == ')' { + mul_enabled = enable; + } + ParserState::Search + } }; } } // Task 1 - println!("Sum of all multiplications: {sum}"); + println!("Sum of all multiplications: {sum_a}"); // Task 2 - // TBD + println!("Sum of all multiplications (do/don't): {sum_b}"); Ok(()) }