Skip to main content

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        let (groups, []) = self.input.as_chunks::<3>() else {
30            panic!("expected number of rows to be a multiple of 3");
31        };
32        groups
33            .iter()
34            .flat_map(|w| {
35                (0..3).map(|i| usize::from(Self::valid_triangle(w[0][i], w[1][i], w[2][i])))
36            })
37            .sum()
38    }
39
40    fn valid_triangle(a: u32, b: u32, c: u32) -> bool {
41        let sum = a + b + c;
42        let max = a.max(b).max(c);
43        // This isn't checking for overflow, but that the shortest 2 sides (sum - max) are longer
44        // than the longest side
45        sum - max > max
46    }
47}
48
49examples!(Day03 -> (usize, usize) [
50    {input: "5 10 25", part1: 0},
51]);