aoc/year2019/
day01.rs

1//! # The Tyranny of the Rocket Equation
2//!
3//! The title of the problem is a reference to the
4//! [real life equation](https://en.wikipedia.org/wiki/Tsiolkovsky_rocket_equation).
5use crate::util::parse::*;
6
7/// The [`iter_unsigned`] utility method extracts and parses numbers from surrounding text.
8///
9/// [`iter_unsigned`]: crate::util::parse
10pub fn parse(input: &str) -> Vec<u32> {
11    input.iter_unsigned().collect()
12}
13
14/// Calculate fuel requirements following the formula.
15pub fn part1(input: &[u32]) -> u32 {
16    input.iter().map(|mass| mass / 3 - 2).sum()
17}
18
19/// Calculate the fuel requirements taking into account that fuel needs more fuel to lift it.
20/// Mass of 8 or below results in zero or negative fuel so we can stop.
21pub fn part2(input: &[u32]) -> u32 {
22    input
23        .iter()
24        .copied()
25        .map(|mut mass| {
26            let mut fuel = 0;
27            while mass > 8 {
28                mass = mass / 3 - 2;
29                fuel += mass;
30            }
31            fuel
32        })
33        .sum()
34}