This commit is contained in:
Aaron Manning 2024-12-06 18:18:50 +11:00
parent 7bf66496af
commit 85c095c74d
3 changed files with 83 additions and 0 deletions

7
day-03/Cargo.lock generated Normal file
View File

@ -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"

6
day-03/Cargo.toml Normal file
View File

@ -0,0 +1,6 @@
[package]
name = "day-03"
version = "0.1.0"
edition = "2021"
[dependencies]

70
day-03/src/main.rs Normal file
View File

@ -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::<u32>(&src[start..idx]).unwrap(), idx))
} else { None }
}
fn parse_lit(src: &str, idx: usize, exp: &str) -> Option<usize> {
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))
}