|
| 1 | +use std::collections::HashMap; |
| 2 | +use std::str::FromStr; |
| 3 | + |
| 4 | +#[derive(Debug)] |
| 5 | +pub struct ParseError; |
| 6 | + |
| 7 | +#[derive(Debug, Default)] |
| 8 | +pub struct Puzzle { |
| 9 | + pub parts: Vec<Part>, |
| 10 | + pub symbols: HashMap<(usize, usize), Symbol>, |
| 11 | +} |
| 12 | + |
| 13 | +impl FromStr for Puzzle { |
| 14 | + type Err = ParseError; |
| 15 | + |
| 16 | + fn from_str(s: &str) -> Result<Self, Self::Err> { |
| 17 | + let mut puzzle = Puzzle::default(); |
| 18 | + for (row, line) in s.lines().enumerate() { |
| 19 | + let mut parsing_part = false; |
| 20 | + for (col, ch) in line.chars().enumerate() { |
| 21 | + match ch { |
| 22 | + '0'..='9' => { |
| 23 | + if !parsing_part { |
| 24 | + parsing_part = true; |
| 25 | + puzzle.parts.push(Part { |
| 26 | + number: 0, |
| 27 | + row, |
| 28 | + col, |
| 29 | + len: 0, |
| 30 | + }); |
| 31 | + } |
| 32 | + let part = puzzle.parts.last_mut().unwrap(); |
| 33 | + part.number = part.number * 10 + ch.to_digit(10).unwrap(); |
| 34 | + part.len += 1; |
| 35 | + } |
| 36 | + '.' => parsing_part = false, |
| 37 | + _ => { |
| 38 | + puzzle.symbols.insert((row, col), Symbol(ch)); |
| 39 | + parsing_part = false; |
| 40 | + } |
| 41 | + } |
| 42 | + } |
| 43 | + } |
| 44 | + Ok(puzzle) |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +#[derive(Debug)] |
| 49 | +pub struct Part { |
| 50 | + pub number: u32, |
| 51 | + pub row: usize, |
| 52 | + pub col: usize, |
| 53 | + pub len: usize, |
| 54 | +} |
| 55 | + |
| 56 | +impl Part { |
| 57 | + pub fn adjacent_points(&self) -> impl IntoIterator<Item = (usize, usize)> { |
| 58 | + let min_col = self.col.saturating_sub(1); |
| 59 | + let max_col = self.col + self.len; |
| 60 | + let min_row = self.row.saturating_sub(1); |
| 61 | + let max_row = self.row + 1; |
| 62 | + let top = (min_col..=max_col).map(move |col| (min_row, col)); |
| 63 | + let mid = [min_col, max_col].map(|col| (self.row, col)); |
| 64 | + let bot = (min_col..=max_col).map(move |col| (max_row, col)); |
| 65 | + top.chain(mid).chain(bot) |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +#[derive(Debug)] |
| 70 | +pub struct Symbol(char); |
| 71 | + |
| 72 | +impl Symbol { |
| 73 | + pub fn is_gear(&self) -> bool { |
| 74 | + self.0 == '*' |
| 75 | + } |
| 76 | +} |
0 commit comments