Day3 Part 1

trunk
Erin 2023-12-04 08:00:02 +01:00
parent 2693e3ee9b
commit 22e7f6014c
2 changed files with 72 additions and 0 deletions

View File

@ -4,5 +4,8 @@ version = "0.1.0"
edition = "2021"
license = "MIT"
[profile.release]
lto = true
[dependencies]
color-eyre = "0.6"

69
src/bin/day03.rs Normal file
View File

@ -0,0 +1,69 @@
use color_eyre::{
eyre::{bail, ensure},
Result,
};
use std::io::stdin;
fn part1(
matrix: &[u8],
cols: usize,
) -> Result<impl Iterator<Item = Result<u64, std::num::ParseIntError>> + '_> {
let cols_sig = isize::try_from(cols)?;
Ok(matrix
.chunks(cols)
.flat_map(|chunk| chunk.split(|pred| !(*pred as char).is_ascii_digit()))
.filter(|s| !s.is_empty())
.map(move |slice| {
let ix = slice.as_ptr() as usize - matrix.as_ptr() as usize;
(ix..slice.len() + ix)
.flat_map(|ix| {
(ix % cols != 0)
.then_some([-1, cols_sig - 1, -cols_sig - 1])
.into_iter()
.chain((ix % cols != cols - 1).then_some([1, cols_sig + 1, -cols_sig + 1]))
.flatten()
.chain([-cols_sig, cols_sig])
.flat_map(move |offset| ix.checked_add_signed(offset))
})
.flat_map(|ix| matrix.get(ix))
.any(|&b| (b as char).is_ascii_punctuation() && b != b'.')
.then(|| String::from_utf8_lossy(slice).parse::<u64>())
.transpose()
.map(|x| x.unwrap_or_default())
}))
}
fn part2(matrix: &[u8], cols: usize) -> Result<impl Iterator<Item = Result<u64>> + '_> {
Ok(std::iter::once(Ok(0)))
}
fn main() -> Result<()> {
let mut lines = stdin().lines();
let line = match lines.next() {
Some(Ok(line)) => line,
Some(Err(e)) => bail!(e),
None => {
println!("0");
return Ok(());
}
};
let cols = line.len();
let mut matrix = line.as_bytes().to_owned();
lines.try_for_each(|ln| {
let ln = ln?;
ensure!(ln.len() == cols, "Invalid column count");
matrix.extend_from_slice(ln.as_bytes());
Ok(())
})?;
println!(
"{}",
part1(&matrix, cols)?.try_fold::<_, _, Result<_>>(0, |acc, x| Ok(acc + x?))?
);
Ok(())
}