1type 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 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}