diff --git a/day-03/Cargo.lock b/day-03/Cargo.lock new file mode 100644 index 0000000..17695b0 --- /dev/null +++ b/day-03/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "day-03" +version = "0.1.0" diff --git a/day-03/Cargo.toml b/day-03/Cargo.toml new file mode 100644 index 0000000..94ea66c --- /dev/null +++ b/day-03/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "day-03" +version = "0.1.0" +edition = "2021" + +[dependencies] diff --git a/day-03/src/main.rs b/day-03/src/main.rs new file mode 100644 index 0000000..1c8797a --- /dev/null +++ b/day-03/src/main.rs @@ -0,0 +1,70 @@ +const INPUT: &str = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/input.txt")); + +fn main() { + let mut idx = 0; + let mut total = 0; + while idx < INPUT.len() { + if let Some((num, temp)) = parse_mul(INPUT, idx) { + total += num; + idx = temp; + } else { + idx += 1; + } + } + + println!("Part 1: {}", total); + + let mut idx = 0; + let mut conditional = 0; + let mut permitted = true; + while idx < INPUT.len() { + if let Some(temp) = parse_lit(INPUT, idx, "do()") { + idx = temp; + permitted = true; + } else if let Some(temp) = parse_lit(INPUT, idx, "don't()") { + idx = temp; + permitted = false; + } + else if let Some((num, temp)) = parse_mul(INPUT, idx) { + idx = temp; + + if permitted { + conditional += num; + } + } else { + idx += 1; + } + } + + println!("Part 2: {}", conditional); +} + +fn parse_num(src: &str, mut idx: usize) -> Option<(u32, usize)> { + let start = idx; + let mut chars = src[idx..].chars(); + while chars.next().is_some_and(|c| c.is_numeric()) { + idx += 1; + } + + if idx != start { + Some((str::parse::(&src[start..idx]).unwrap(), idx)) + } else { None } +} + +fn parse_lit(src: &str, idx: usize, exp: &str) -> Option { + if src[idx..].starts_with(exp) { + Some(idx + exp.len()) + } else { + None + } +} + +fn parse_mul(src: &str, mut idx: usize) -> Option<(u32, usize)> { + idx = parse_lit(src, idx, "mul(")?; + let (first, mut idx) = parse_num(src, idx)?; + idx = parse_lit(src, idx, ",")?; + let (second, mut idx) = parse_num(src, idx)?; + idx = parse_lit(src, idx, ")")?; + + Some((first * second, idx)) +}