year2016/
day03.rs

1use utils::prelude::*;
2
3/// Checking triangle validity.
4#[derive(Clone, Debug)]
5pub struct Day03 {
6    input: Vec<[u32; 3]>,
7}
8
9impl Day03 {
10    pub fn new(input: &str, _: InputType) -> Result<Self, InputError> {
11        Ok(Self {
12            input: parser::u32()
13                .with_prefix(parser::take_while(u8::is_ascii_whitespace))
14                .repeat_n(parser::noop())
15                .parse_lines(input)?,
16        })
17    }
18
19    #[must_use]
20    pub fn part1(&self) -> usize {
21        self.input
22            .iter()
23            .filter(|&&[a, b, c]| Self::valid_triangle(a, b, c))
24            .count()
25    }
26
27    #[must_use]
28    pub fn part2(&self) -> usize {
29        self.input
30            .chunks_exact(3)
31            .flat_map(|w| {
32                (0..3).map(|i| usize::from(Self::valid_triangle(w[0][i], w[1][i], w[2][i])))
33            })
34            .sum()
35    }
36
37    fn valid_triangle(a: u32, b: u32, c: u32) -> bool {
38        let sum = a + b + c;
39        let max = a.max(b).max(c);
40        // This isn't checking for overflow, but that the shortest 2 sides (sum - max) are longer
41        // than the longest side
42        sum - max > max
43    }
44}
45
46examples!(Day03 -> (usize, usize) [
47    {input: "5 10 25", part1: 0},
48]);