Day 01 - The Tyranny of the Rocket Equation

mathiteration

Language: Rust

Problem https://adventofcode.com/2019/day/1


Part 1: Each line is a module mass. Fuel required is mass / 3 - 2 (integer division). Sum it across all modules:

for num in numbers.iter() {
    total_fuel += num / 3 - 2;
}

Simple enough.


Part 2: Fuel itself has mass and needs its own fuel. Keep applying the formula until the result hits zero or goes negative, adding each positive result to the total.

I use a loop per module that keeps recalculating on the previous fuel amount until it bottoms out:

for &module in &numbers {
    let mut current_mass = module;
    loop {
        let fuel = current_mass / 3 - 2;
        if fuel <= 0 {
            break;
        }
        total_fuel += fuel;
        current_mass = fuel;
    }
}

The loop converges quickly since the fuel shrinks fast with each step.


Solution: https://github.com/Elyrial/AdventOfCode/blob/main/src/solutions/year2019/day01.rs

No C writeup yet.