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