|
| 1 | +extern crate nalgebra as na; |
| 2 | +use na::{DMatrix, Matrix3, matrix}; |
| 3 | + |
| 4 | +use std::fs; |
| 5 | + |
| 6 | +#[derive(Debug)] |
| 7 | +struct Puzzle { |
| 8 | + height: usize, |
| 9 | + width: usize, |
| 10 | + map: DMatrix<u32>, |
| 11 | + mas_height: usize, |
| 12 | + mas_width: usize, |
| 13 | + xmases: Vec<Matrix3<u32>>, |
| 14 | +} |
| 15 | + |
| 16 | +impl Puzzle { |
| 17 | + fn new(data: &str) -> Puzzle { |
| 18 | + let height = data.lines().count(); |
| 19 | + let width = data.lines().nth(0).unwrap().chars().count(); |
| 20 | + |
| 21 | + let mut map = DMatrix::zeros(height, width); |
| 22 | + |
| 23 | + for (row, line) in data.lines().enumerate() { |
| 24 | + for (col, c) in line.chars().enumerate() { |
| 25 | + map[(row, col)] = c as u32; |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + let mas1 = matrix!['M' as u32, '.' as u32, 'S' as u32; |
| 30 | + '.' as u32, 'A' as u32, '.' as u32; |
| 31 | + 'M' as u32, '.' as u32, 'S' as u32]; |
| 32 | + let mas2 = matrix![0, 0, 1; |
| 33 | + 0, 1, 0; |
| 34 | + 1, 0, 0] * mas1.transpose(); |
| 35 | + let mas3 = matrix![0, 0, 1; |
| 36 | + 0, 1, 0; |
| 37 | + 1, 0, 0] * mas2.transpose(); |
| 38 | + let mas4 = matrix![0, 0, 1; |
| 39 | + 0, 1, 0; |
| 40 | + 1, 0, 0] * mas3.transpose(); |
| 41 | + let xmases = vec![ |
| 42 | + mas1, |
| 43 | + mas2, |
| 44 | + mas3, |
| 45 | + mas4, |
| 46 | + ]; |
| 47 | + |
| 48 | + Puzzle { |
| 49 | + height, |
| 50 | + width, |
| 51 | + map, |
| 52 | + mas_height: 3, |
| 53 | + mas_width: 3, |
| 54 | + xmases, |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + fn match_p(&self, y: usize, x: usize) -> bool { |
| 59 | + self.xmases.iter().any(|&xmas| { |
| 60 | + let mut res = true; |
| 61 | + for my in 0..self.mas_height { |
| 62 | + for mx in 0..self.mas_width { |
| 63 | + if xmas[(my, mx)] == '.' as u32 { continue } |
| 64 | + |
| 65 | + if xmas[(my, mx)] != self.map[(y + my, x + mx)] { |
| 66 | + res = false |
| 67 | + } |
| 68 | + } |
| 69 | + } |
| 70 | + res |
| 71 | + }) |
| 72 | + } |
| 73 | + |
| 74 | + fn count_matches(&self) -> i32 { |
| 75 | + let mut count = 0; |
| 76 | + |
| 77 | + for y in 0..=(self.height - self.mas_height) { |
| 78 | + for x in 0..=(self.width - self.mas_width) { |
| 79 | + if self.match_p(y, x) { count += 1 } |
| 80 | + } |
| 81 | + } |
| 82 | + |
| 83 | + count |
| 84 | + } |
| 85 | +} |
| 86 | + |
| 87 | +fn main() { |
| 88 | + let input = fs::read_to_string("../04.input").unwrap(); |
| 89 | + |
| 90 | + let p = Puzzle::new(&input); |
| 91 | + |
| 92 | + println!("{}", p.count_matches()); |
| 93 | +} |
0 commit comments