|
| 1 | +use utils::prelude::*; |
| 2 | + |
| 3 | +/// Adding matching digits. |
| 4 | +#[derive(Clone, Debug)] |
| 5 | +pub struct Day01<'a> { |
| 6 | + input: &'a [u8], |
| 7 | +} |
| 8 | + |
| 9 | +impl<'a> Day01<'a> { |
| 10 | + pub fn new(input: &'a str, _: InputType) -> Result<Self, InputError> { |
| 11 | + if let Some(b) = input.bytes().find(|b| !b.is_ascii_digit()) { |
| 12 | + Err(InputError::new(input, b as char, "expected digit")) |
| 13 | + } else { |
| 14 | + Ok(Self { |
| 15 | + input: input.as_bytes(), |
| 16 | + }) |
| 17 | + } |
| 18 | + } |
| 19 | + |
| 20 | + #[must_use] |
| 21 | + pub fn part1(&self) -> u32 { |
| 22 | + self.input |
| 23 | + .iter() |
| 24 | + .zip(self.input.iter().cycle().skip(1)) |
| 25 | + .map(|(&a, &b)| if a == b { (a - b'0') as u32 } else { 0 }) |
| 26 | + .sum() |
| 27 | + } |
| 28 | + |
| 29 | + #[must_use] |
| 30 | + pub fn part2(&self) -> u32 { |
| 31 | + self.input |
| 32 | + .iter() |
| 33 | + .zip(self.input.iter().cycle().skip(self.input.len() / 2)) |
| 34 | + .map(|(&a, &b)| if a == b { (a - b'0') as u32 } else { 0 }) |
| 35 | + .sum() |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +examples!(Day01<'_> -> (u32, u32) [ |
| 40 | + {input: "1122", part1: 3}, |
| 41 | + {input: "1111", part1: 4}, |
| 42 | + {input: "1234", part1: 0}, |
| 43 | + {input: "91212129", part1: 9}, |
| 44 | + {input: "1212", part2: 6}, |
| 45 | + {input: "1221", part2: 0}, |
| 46 | + {input: "123425", part2: 4}, |
| 47 | + {input: "123123", part2: 12}, |
| 48 | + {input: "12131415", part2: 4}, |
| 49 | +]); |
0 commit comments