Skip to main content

aoc/year2023/
day13.rs

1//! # Point of Incidence
2//!
3//! We store each row of a grid as a binary number. For example `#.##..##.` becomes `101100110`.
4//! Then to count smudges we bitwise XOR the respective rows together and count one bits
5//! using the [`count_ones`] function.
6//!
7//! For example:
8//! ```none
9//!  ..##..###     001100111 ^ 000100111 = 001000000 => 1
10//! v#####.##.v => 111110110 ^ 111110110 = 000000000 => 0
11//! ^#####.##.^
12//!  ...#..###
13//! ```
14//!
15//! To handle columns we transpose the grid then convert into integers the same way. For part one
16//! we look for a reflection axis with 0 smudges and for part two 1 smudge, allowing the same
17//! code to be reused.
18//!
19//! [`count_ones`]: u32::count_ones
20type Input = Vec<(Vec<u32>, Vec<u32>)>;
21
22pub fn parse(input: &str) -> Input {
23    input
24        .split("\n\n")
25        .map(|block| {
26            let grid: Vec<_> = block.lines().map(str::as_bytes).collect();
27            let (width, height) = (grid[0].len(), grid.len());
28            let bit = |x: usize, y: usize| u32::from(grid[y][x] == b'#');
29
30            let rows = Vec::from_fn(height, |y| (0..width).fold(0, |n, x| (n << 1) | bit(x, y)));
31            let columns = Vec::from_fn(width, |x| (0..height).fold(0, |n, y| (n << 1) | bit(x, y)));
32
33            (rows, columns)
34        })
35        .collect()
36}
37
38pub fn part1(input: &Input) -> usize {
39    reflect(input, 0)
40}
41
42pub fn part2(input: &Input) -> usize {
43    reflect(input, 1)
44}
45
46fn reflect(input: &Input, target: u32) -> usize {
47    input
48        .iter()
49        .map(|(rows, columns)| {
50            reflect_axis(columns, target)
51                .unwrap_or_else(|| 100 * reflect_axis(rows, target).unwrap())
52        })
53        .sum()
54}
55
56fn reflect_axis(axis: &[u32], target: u32) -> Option<usize> {
57    (1..axis.len()).find(|&i| {
58        // Zip stops when either side reaches the boundary of the grid.
59        let smudges: u32 =
60            axis[..i].iter().rev().zip(&axis[i..]).map(|(a, b)| (a ^ b).count_ones()).sum();
61
62        smudges == target
63    })
64}