1use utils::grid;
2use utils::prelude::*;
3
4#[derive(Clone, Debug)]
6pub struct Day04 {
7 cols: usize,
8 grid: Vec<u8>,
9}
10
11impl Day04 {
12 pub fn new(input: &str, _: InputType) -> Result<Self, InputError> {
13 let (_, cols, grid) = grid::parse(
14 input,
15 3,
16 0,
17 |b| b,
18 |b| matches!(b, b'X' | b'M' | b'A' | b'S'),
19 |_, _| Err("expected 'X', 'M', 'A', 'S'"),
20 )?;
21 Ok(Self { cols, grid })
22 }
23
24 #[must_use]
25 pub fn part1(&self) -> u32 {
26 self.check_offset(self.cols as isize)
27 + self.check_offset(-(self.cols as isize))
28 + self.check_offset(1)
29 + self.check_offset(-1)
30 + self.check_offset((self.cols as isize) + 1)
31 + self.check_offset((self.cols as isize) - 1)
32 + self.check_offset(-(self.cols as isize) + 1)
33 + self.check_offset(-(self.cols as isize) - 1)
34 }
35
36 fn check_offset(&self, offset: isize) -> u32 {
37 let start = 3 * self.cols + 3;
38 let mut count = 0;
39 for (((first, second), third), fourth) in self.grid[start..]
40 .iter()
41 .zip(&self.grid[start.wrapping_add_signed(offset)..])
42 .zip(&self.grid[start.wrapping_add_signed(offset * 2)..])
43 .zip(&self.grid[start.wrapping_add_signed(offset * 3)..])
44 {
45 count += u32::from(
46 (*first == b'X') & (*second == b'M') & (*third == b'A') & (*fourth == b'S'),
47 );
48 }
49 count
50 }
51
52 #[must_use]
53 pub fn part2(&self) -> u32 {
54 let mut count = 0;
55 for ((((middle, nw), ne), sw), se) in self.grid[self.cols * 4 + 4..]
56 .iter()
57 .zip(&self.grid[self.cols * 3 + 3..])
58 .zip(&self.grid[self.cols * 3 + 5..])
59 .zip(&self.grid[self.cols * 5 + 3..])
60 .zip(&self.grid[self.cols * 5 + 5..])
61 {
62 count += u32::from(
63 (*middle == b'A') & ((*nw ^ *se) == (b'M' ^ b'S')) & ((*ne ^ *sw) == (b'M' ^ b'S')),
64 );
65 }
66 count
67 }
68}
69
70examples!(Day04 -> (u32, u32) [
71 {file: "day04_example0.txt", part1: 18, part2: 9},
72]);