|
| 1 | +use utils::grid; |
| 2 | +use utils::prelude::*; |
| 3 | + |
| 4 | +/// Counting matches in a word search. |
| 5 | +#[derive(Clone, Debug)] |
| 6 | +pub struct Day04 { |
| 7 | + rows: usize, |
| 8 | + cols: usize, |
| 9 | + grid: Vec<u8>, |
| 10 | +} |
| 11 | + |
| 12 | +impl Day04 { |
| 13 | + pub fn new(input: &str, _: InputType) -> Result<Self, InputError> { |
| 14 | + let (rows, cols, grid) = grid::from_str_padded(input, 3, b'\0', |c| match c { |
| 15 | + b'X' | b'M' | b'A' | b'S' => Some(c), |
| 16 | + _ => None, |
| 17 | + })?; |
| 18 | + Ok(Self { rows, cols, grid }) |
| 19 | + } |
| 20 | + |
| 21 | + #[must_use] |
| 22 | + pub fn part1(&self) -> u32 { |
| 23 | + let offsets = [ |
| 24 | + self.cols as isize, |
| 25 | + -(self.cols as isize), |
| 26 | + 1, |
| 27 | + -1, |
| 28 | + (self.cols as isize) + 1, |
| 29 | + (self.cols as isize) - 1, |
| 30 | + -(self.cols as isize) + 1, |
| 31 | + -(self.cols as isize) - 1, |
| 32 | + ]; |
| 33 | + |
| 34 | + let mut count = 0; |
| 35 | + for r in 3..self.rows - 3 { |
| 36 | + for c in 3..self.cols - 3 { |
| 37 | + let i = r * self.cols + c; |
| 38 | + if self.grid[i] != b'X' { |
| 39 | + continue; |
| 40 | + } |
| 41 | + |
| 42 | + for o in offsets { |
| 43 | + if self.grid[i.wrapping_add_signed(o)] == b'M' |
| 44 | + && self.grid[i.wrapping_add_signed(o * 2)] == b'A' |
| 45 | + && self.grid[i.wrapping_add_signed(o * 3)] == b'S' |
| 46 | + { |
| 47 | + count += 1; |
| 48 | + } |
| 49 | + } |
| 50 | + } |
| 51 | + } |
| 52 | + count |
| 53 | + } |
| 54 | + |
| 55 | + #[must_use] |
| 56 | + pub fn part2(&self) -> u32 { |
| 57 | + let mut count = 0; |
| 58 | + for r in 4..self.rows - 4 { |
| 59 | + for c in 4..self.cols - 4 { |
| 60 | + let i = r * self.cols + c; |
| 61 | + if self.grid[i] != b'A' { |
| 62 | + continue; |
| 63 | + } |
| 64 | + |
| 65 | + let (nw, ne, sw, se) = ( |
| 66 | + self.grid[i.wrapping_add_signed(-(self.cols as isize) - 1)], |
| 67 | + self.grid[i.wrapping_add_signed(-(self.cols as isize) + 1)], |
| 68 | + self.grid[i.wrapping_add_signed((self.cols as isize) - 1)], |
| 69 | + self.grid[i.wrapping_add_signed((self.cols as isize) + 1)], |
| 70 | + ); |
| 71 | + |
| 72 | + // Given each variable is one of (b'\0', b'X', b'M', b'A', b'S') this is |
| 73 | + // equivalent to and slightly faster than |
| 74 | + // ((nw == b'M' && se == b'S') || (nw == b'S' && se == b'M')) |
| 75 | + // && ((ne == b'M' && sw == b'S') || (ne == b'S' && sw == b'M')) |
| 76 | + // As no other pair XORed equals b'M' ^ b'S' |
| 77 | + if (nw ^ se) == (b'M' ^ b'S') && (ne ^ sw) == (b'M' ^ b'S') { |
| 78 | + count += 1; |
| 79 | + } |
| 80 | + } |
| 81 | + } |
| 82 | + count |
| 83 | + } |
| 84 | +} |
| 85 | + |
| 86 | +examples!(Day04 -> (u32, u32) [ |
| 87 | + {file: "day04_example0.txt", part1: 18, part2: 9}, |
| 88 | +]); |
0 commit comments