2019: day01: part 2
This commit is contained in:
parent
22fcfdae4f
commit
5e2fb25c94
|
@ -4,12 +4,16 @@ const INPUT: &str = include_str!("../input/day01.txt");
|
||||||
|
|
||||||
pub fn run() -> Result<()> {
|
pub fn run() -> Result<()> {
|
||||||
println!("part 1: {}", part1(INPUT)?);
|
println!("part 1: {}", part1(INPUT)?);
|
||||||
|
println!("part 2: {}", part2(INPUT)?);
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn fuel_needed(module_weight: u64) -> u64 {
|
fn fuel_needed(module_weight: u64) -> u64 {
|
||||||
(module_weight / 3) - 2
|
match (module_weight / 3).checked_sub(2) {
|
||||||
|
Some(f) => f,
|
||||||
|
None => 0,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn part1(input: &str) -> Result<u64> {
|
fn part1(input: &str) -> Result<u64> {
|
||||||
|
@ -23,6 +27,29 @@ fn part1(input: &str) -> Result<u64> {
|
||||||
.sum()
|
.sum()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn cumulated_fuel_needed(module_weight: u64) -> u64 {
|
||||||
|
let mut total_fuel = fuel_needed(module_weight);
|
||||||
|
let mut additional_fuel = fuel_needed(total_fuel);
|
||||||
|
|
||||||
|
while additional_fuel != 0 {
|
||||||
|
total_fuel += additional_fuel;
|
||||||
|
additional_fuel = fuel_needed(additional_fuel);
|
||||||
|
}
|
||||||
|
|
||||||
|
total_fuel
|
||||||
|
}
|
||||||
|
|
||||||
|
fn part2(input: &str) -> Result<u64> {
|
||||||
|
input
|
||||||
|
.lines()
|
||||||
|
.map(|line| line.parse::<u64>())
|
||||||
|
.map(|w| match w {
|
||||||
|
Ok(w) => Ok(cumulated_fuel_needed(w)),
|
||||||
|
Err(e) => Err(Box::from(e)),
|
||||||
|
})
|
||||||
|
.sum()
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
@ -39,4 +66,16 @@ mod tests {
|
||||||
fn part1_real() {
|
fn part1_real() {
|
||||||
assert_eq!(part1(INPUT).unwrap(), 3268951);
|
assert_eq!(part1(INPUT).unwrap(), 3268951);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn part2_provided() {
|
||||||
|
assert_eq!(cumulated_fuel_needed(14), 2);
|
||||||
|
assert_eq!(cumulated_fuel_needed(1969), 966);
|
||||||
|
assert_eq!(cumulated_fuel_needed(100756), 50346);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn part2_real() {
|
||||||
|
assert_eq!(part2(INPUT).unwrap(), 4900568);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in a new issue