From c6010439ba7398301f9bfa37079f9a0e496c4c15 Mon Sep 17 00:00:00 2001 From: Wesley Moore Date: Mon, 2 Dec 2019 12:10:25 +1100 Subject: [PATCH] Day 1 part 2 --- 2019/src/bin/day1.rs | 31 ++++++++++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/2019/src/bin/day1.rs b/2019/src/bin/day1.rs index a4ec704..eb200d8 100644 --- a/2019/src/bin/day1.rs +++ b/2019/src/bin/day1.rs @@ -3,13 +3,38 @@ use std::io; use advent_of_code::input; fn main() -> io::Result<()> { + let module_masses = input::read_number_list("input/day1.txt")?; + // Specifically, to find the fuel required for a module, take its mass, divide by three, round down, and subtract 2. - let result: i32 = input::read_number_list("input/day1.txt")? + let fuel: Vec<_> = module_masses .into_iter() .map(|module_mass| (module_mass as f64 / 3.).floor() as i32 - 2) - .sum(); + .collect(); - println!("Result: {}", result); + println!("Part 1: {}", fuel.iter().sum::()); + part2(&fuel); Ok(()) } + +fn part2(fuel: &[i32]) { + // Fuel itself requires fuel just like a module - take its mass, divide by three, round down, and subtract 2. + let result: i32 = fuel + .iter() + .map(|&fuel| { + let mut total = 0; + let mut extra = fuel_fuel(fuel); + while extra > 0 { + total += extra; + extra = fuel_fuel(extra); + } + total + }) + .sum(); + + println!("Part 2: {}", result + fuel.iter().sum::()); +} + +fn fuel_fuel(fuel: i32) -> i32 { + ((fuel as f64 / 3.).floor() as i32).saturating_sub(2) +}