year2017/
day02.rs

1use utils::prelude::*;
2
3/// Calculating spreadsheet checksums.
4#[derive(Clone, Debug)]
5pub struct Day02 {
6    rows: Vec<Vec<u32>>,
7}
8
9impl Day02 {
10    pub fn new(input: &str, _: InputType) -> Result<Self, InputError> {
11        Ok(Self {
12            rows: parser::u32()
13                .repeat(b' '.or(b'\t'), 2)
14                .map(|mut v| {
15                    v.sort_unstable();
16                    v
17                })
18                .parse_lines(input)?,
19        })
20    }
21
22    #[must_use]
23    pub fn part1(&self) -> u32 {
24        self.rows
25            .iter()
26            .map(|row| row[row.len() - 1] - row[0])
27            .sum()
28    }
29
30    #[must_use]
31    pub fn part2(&self) -> u32 {
32        self.rows
33            .iter()
34            .map(|row| {
35                for i in 0..row.len() - 1 {
36                    for j in i + 1..row.len() {
37                        if row[j] % row[i] == 0 {
38                            return row[j] / row[i];
39                        }
40                    }
41                }
42                panic!("no solution found")
43            })
44            .sum()
45    }
46}
47
48examples!(Day02 -> (u32, u32) [
49    {input: "5 1 9 5\n7 5 3\n2 4 6 8", part1: 18},
50    {input: "5 9 2 8\n9 4 7 3\n3 8 6 5", part2: 9},
51]);