year2024/
day04.rs

1use utils::grid;
2use utils::prelude::*;
3
4/// Counting matches in a word search.
5#[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::from_str_padded(input, 3, b'\0', |c| match c {
14            b'X' | b'M' | b'A' | b'S' => Some(c),
15            _ => None,
16        })?;
17        Ok(Self { cols, grid })
18    }
19
20    #[must_use]
21    pub fn part1(&self) -> u32 {
22        self.check_offset(self.cols as isize)
23            + self.check_offset(-(self.cols as isize))
24            + self.check_offset(1)
25            + self.check_offset(-1)
26            + self.check_offset((self.cols as isize) + 1)
27            + self.check_offset((self.cols as isize) - 1)
28            + self.check_offset(-(self.cols as isize) + 1)
29            + self.check_offset(-(self.cols as isize) - 1)
30    }
31
32    fn check_offset(&self, offset: isize) -> u32 {
33        let start = 3 * self.cols + 3;
34        let mut count = 0;
35        for (((first, second), third), fourth) in self.grid[start..]
36            .iter()
37            .zip(&self.grid[start.wrapping_add_signed(offset)..])
38            .zip(&self.grid[start.wrapping_add_signed(offset * 2)..])
39            .zip(&self.grid[start.wrapping_add_signed(offset * 3)..])
40        {
41            count += u32::from(
42                (*first == b'X') & (*second == b'M') & (*third == b'A') & (*fourth == b'S'),
43            );
44        }
45        count
46    }
47
48    #[must_use]
49    pub fn part2(&self) -> u32 {
50        let mut count = 0;
51        for ((((middle, nw), ne), sw), se) in self.grid[self.cols * 4 + 4..]
52            .iter()
53            .zip(&self.grid[self.cols * 3 + 3..])
54            .zip(&self.grid[self.cols * 3 + 5..])
55            .zip(&self.grid[self.cols * 5 + 3..])
56            .zip(&self.grid[self.cols * 5 + 5..])
57        {
58            count += u32::from(
59                (*middle == b'A') & ((*nw ^ *se) == (b'M' ^ b'S')) & ((*ne ^ *sw) == (b'M' ^ b'S')),
60            );
61        }
62        count
63    }
64}
65
66examples!(Day04 -> (u32, u32) [
67    {file: "day04_example0.txt", part1: 18, part2: 9},
68]);