day 3
This commit is contained in:
parent
7bf66496af
commit
85c095c74d
7
day-03/Cargo.lock
generated
Normal file
7
day-03/Cargo.lock
generated
Normal 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
6
day-03/Cargo.toml
Normal file
@ -0,0 +1,6 @@
|
||||
[package]
|
||||
name = "day-03"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
70
day-03/src/main.rs
Normal file
70
day-03/src/main.rs
Normal 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))
|
||||
}
|
Loading…
Reference in New Issue
Block a user