Implement 2023 day 13 part 2

This commit is contained in:
2023-12-13 18:33:09 +01:00
parent 0838646973
commit 0c4430ad01

View File

@@ -15,12 +15,16 @@ impl Symmetry {
} }
} }
fn find_symmetry(grid: Grid<'_>) -> Option<Symmetry> { fn find_symmetry(grid: Grid<'_>, differences: usize) -> Option<Symmetry> {
// Attempt to find a vertical line of reflection first // Attempt to find a vertical line of reflection first
for c in 1..grid.width() { for c in 1..grid.width() {
if grid if grid
.rows() .rows()
.all(|row| row[..c].iter().rev().zip(&row[c..]).all(|(a, b)| a == b)) .flat_map(|row| row[..c].iter().rev().zip(&row[c..]))
.filter(|(a, b)| a != b)
.take(differences + 1)
.count()
== differences
{ {
return Some(Symmetry::Vertical(c as u32)); return Some(Symmetry::Vertical(c as u32));
} }
@@ -30,7 +34,11 @@ fn find_symmetry(grid: Grid<'_>) -> Option<Symmetry> {
if (0..r) if (0..r)
.rev() .rev()
.zip(r..grid.height()) .zip(r..grid.height())
.all(|(a, b)| grid[a] == grid[b]) .flat_map(|(a, b)| grid[a].iter().zip(&grid[b]))
.filter(|(a, b)| a != b)
.take(differences + 1)
.count()
== differences
{ {
return Some(Symmetry::Horizontal(r as u32)); return Some(Symmetry::Horizontal(r as u32));
} }
@@ -62,19 +70,23 @@ fn parse_grids(input: &[u8]) -> anyhow::Result<Vec<Grid<'_>>> {
Ok(result) Ok(result)
} }
pub fn part1(input: &[u8]) -> anyhow::Result<String> { fn parts_common(input: &[u8], differences: usize) -> anyhow::Result<String> {
let grids = parse_grids(input)?; let grids = parse_grids(input)?;
let sum: u32 = grids let sum: u32 = grids
.into_iter() .into_iter()
.filter_map(find_symmetry) .filter_map(|grid| find_symmetry(grid, differences))
.map(Symmetry::value) .map(Symmetry::value)
.sum(); .sum();
Ok(sum.to_string()) Ok(sum.to_string())
} }
pub fn part2(_input: &[u8]) -> anyhow::Result<String> { pub fn part1(input: &[u8]) -> anyhow::Result<String> {
anyhow::bail!("Not implemented") parts_common(input, 0)
}
pub fn part2(input: &[u8]) -> anyhow::Result<String> {
parts_common(input, 1)
} }
#[cfg(test)] #[cfg(test)]
@@ -88,8 +100,8 @@ mod tests {
assert_eq!("405", part1(SAMPLE).unwrap()); assert_eq!("405", part1(SAMPLE).unwrap());
} }
// #[test] #[test]
// fn sample_part2() { fn sample_part2() {
// assert_eq!("525152", part2(SAMPLE).unwrap()); assert_eq!("400", part2(SAMPLE).unwrap());
// } }
} }