year2019/
day01.rs

1use utils::prelude::*;
2
3/// Summing values from a recursive formula.
4#[derive(Clone, Debug)]
5pub struct Day01 {
6    modules: Vec<u32>,
7}
8
9impl Day01 {
10    pub fn new(input: &str, _: InputType) -> Result<Self, InputError> {
11        Ok(Self {
12            modules: parser::u32().parse_lines(input)?,
13        })
14    }
15
16    #[must_use]
17    pub fn part1(&self) -> u32 {
18        self.modules
19            .iter()
20            .map(|mass| (mass / 3).saturating_sub(2))
21            .sum()
22    }
23
24    #[must_use]
25    pub fn part2(&self) -> u32 {
26        self.modules
27            .iter()
28            .map(|&(mut mass)| {
29                let mut fuel = 0;
30                while mass > 0 {
31                    mass = (mass / 3).saturating_sub(2);
32                    fuel += mass;
33                }
34                fuel
35            })
36            .sum()
37    }
38}
39
40examples!(Day01 -> (u32, u32) [
41    {input: "12", part1: 2, part2: 2},
42    {input: "14", part1: 2, part2: 2},
43    {input: "1969", part1: 654, part2: 966},
44    {input: "100756", part1: 33583, part2: 50346},
45]);