advent-of-code/2019/01/day1.rs

32 lines
653 B
Rust
Raw Permalink Normal View History

2019-12-01 19:00:25 +01:00
use std::io::{self, BufRead};
use std::ops::Div;
fn main() {
let lines: Vec<u32> = io::stdin()
.lock()
.lines()
.map(|l| l.unwrap().parse().unwrap())
.collect();
2020-02-26 19:28:45 +01:00
println!("Part 1: {}", part1(&lines));
println!("Part 2: {}", part2(&lines));
2019-12-01 19:00:25 +01:00
}
2020-02-26 19:28:45 +01:00
fn part1(numbers: &Vec<u32>) -> u32 {
numbers.iter().map(|&m| cost(m)).sum()
2019-12-01 19:00:25 +01:00
}
2020-02-26 19:28:45 +01:00
fn part2(numbers: &Vec<u32>) -> u32 {
numbers.iter().map(|&m| cost_rec(m, 0)).sum()
2019-12-01 19:00:25 +01:00
}
fn cost(mass: u32) -> u32 {
mass.div(3).saturating_sub(2)
}
fn cost_rec(mass: u32, acc: u32) -> u32 {
2019-12-01 20:26:37 +01:00
match cost(mass) {
2019-12-01 19:00:25 +01:00
0 => acc,
2019-12-01 20:26:37 +01:00
c => cost_rec(c, acc + c)
2019-12-01 19:00:25 +01:00
}
}