diff --git a/rs/Cargo.lock b/rs/Cargo.lock index 11e3f06..57b6ac2 100644 --- a/rs/Cargo.lock +++ b/rs/Cargo.lock @@ -28,7 +28,6 @@ name = "aoc2024" version = "0.1.0" dependencies = [ "criterion", - "if_chain", "indoc", "itertools 0.13.0", "pretty_assertions", @@ -205,12 +204,6 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fbf6a919d6cf397374f7dfeeea91d974c7c0a7221d0d0f4f20d859d329e53fcc" -[[package]] -name = "if_chain" -version = "1.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb56e1aa765b4b4f3aadfab769793b7087bb03a4ea4920644a6d238e2df5b9ed" - [[package]] name = "indoc" version = "2.0.5" diff --git a/rs/Cargo.toml b/rs/Cargo.toml index 10b1a8e..d2bc545 100644 --- a/rs/Cargo.toml +++ b/rs/Cargo.toml @@ -17,7 +17,6 @@ name = "aoc2024" path = "src/main.rs" [dependencies] -if_chain = "1.0.2" itertools = "0.13" [dev-dependencies] diff --git a/rs/src/day3.rs b/rs/src/day3.rs index ad91e80..95b259d 100644 --- a/rs/src/day3.rs +++ b/rs/src/day3.rs @@ -1,38 +1,27 @@ -use if_chain::if_chain; +use std::iter::successors; pub fn part1(data: &str) -> i32 { - const PREFIX: &str = "mul("; - - let mut data = data; - let mut total = 0; - while let Some(offset) = data.find(PREFIX) { - data = data[offset..].strip_prefix(PREFIX).unwrap(); - if_chain! { - if let Some((a, b)) = data.split_once(','); - if let Ok(a) = a.parse::(); - if let Some((b, c)) = b.split_once(')'); - if let Ok(b) = b.parse::(); - then { - data = c; - total += a * b; - } - } - } - total + data.split("mul(") + .skip(1) + .filter_map(|data| { + let (a, data) = data.split_once(',')?; + let a = a.parse::().ok()?; + let (b, _) = data.split_once(')')?; + let b = b.parse::().ok()?; + Some(a * b) + }) + .sum::() } pub fn part2(data: &str) -> i32 { - let mut data = data; - let mut total = 0; - while !data.is_empty() { - let end = data.find("don't()").unwrap_or(data.len()); - total += part1(&data[..end]); - let Some(start) = data[end..].find("do()") else { - break; - }; - data = &data[end + start..]; + fn split_end(data: &str) -> (&str, &str) { + data.split_once("don't()").unwrap_or((data, "")) } - total + successors(Some(split_end(data)), |(_, data)| { + Some(split_end(data.split_once("do()")?.1)) + }) + .map(|(data, _)| part1(data)) + .sum() } #[cfg(test)]