diff --git a/Cargo.toml b/Cargo.toml index 869f72f..1bba829 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,5 +4,8 @@ version = "0.1.0" edition = "2021" license = "MIT" +[profile.release] +lto = true + [dependencies] color-eyre = "0.6" diff --git a/src/bin/day03.rs b/src/bin/day03.rs new file mode 100644 index 0000000..e8b7785 --- /dev/null +++ b/src/bin/day03.rs @@ -0,0 +1,69 @@ +use color_eyre::{ + eyre::{bail, ensure}, + Result, +}; +use std::io::stdin; + +fn part1( + matrix: &[u8], + cols: usize, +) -> Result> + '_> { + 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::()) + .transpose() + .map(|x| x.unwrap_or_default()) + })) +} + +fn part2(matrix: &[u8], cols: usize) -> Result> + '_> { + + 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(()) +}