Day3 Part 1
This commit is contained in:
parent
2693e3ee9b
commit
22e7f6014c
|
@ -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
69
src/bin/day03.rs
Normal 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(())
|
||||
}
|
Loading…
Reference in a new issue