Skip to main content

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::*;
6use std::iter::successors;
7
8/// The [`iter_unsigned`] utility method extracts and parses numbers from surrounding text.
9///
10/// [`iter_unsigned`]: crate::util::parse
11pub fn parse(input: &str) -> Vec<u32> {
12    input.iter_unsigned().collect()
13}
14
15/// Calculate fuel requirements following the formula.
16pub fn part1(input: &[u32]) -> u32 {
17    input.iter().map(|mass| mass / 3 - 2).sum()
18}
19
20/// Calculate the fuel requirements taking into account that fuel needs more fuel to lift it.
21/// Mass of 8 or below results in zero or negative fuel so we can stop.
22pub fn part2(input: &[u32]) -> u32 {
23    input
24        .iter()
25        .flat_map(|&mass| successors(Some(mass), |&m| (m > 8).then(|| m / 3 - 2)).skip(1))
26        .sum()
27}