Advent of Code 2019 - Day 1

Advent of CodeRust

Advent of Code has started again and I'm attempting to solve the challenges using the Rust programming language and I thought I can also post about it.

My solutions can be found in this repository, along with tests and benchmarks. I'm going to try to solve each challenge on the day it releases but with work, school and other things going on I'm not going to make that. Especially when later challenges are getting more difficult.

Day 1 was really simple and I managed to solve it in about 10 minutes. Iterators are quite handy in Rust for solving this kind of challenge. There's also a tiny bit of recursion to make it more interesting.

Code

fn calculate_fuel(mass: i32) -> i32 {
    let fuel = mass / 3 - 2;
    if fuel <= 0 {
        0
    } else {
        fuel + calculate_fuel(fuel)
    }
}

pub fn part_one(input: &str) -> i32 {
    input
        .lines()
        .map(|x| x.parse::<i32>().unwrap())
        .map(|mass| mass / 3 - 2)
        .sum()
}

pub fn part_two(input: &str) -> i32 {
    input
        .lines()
        .map(|x| x.parse::<i32>().unwrap())
        .map(|mass| calculate_fuel(mass))
        .sum()
}

Benchmarks

2019 - Day 01 - Part 1  time:   [5.1454 us 5.2587 us 5.3996 us]
2019 - Day 01 - Part 2  time:   [9.7581 us 9.9443 us 10.144 us]

Feedback or Questions?

I don't have a direct way to leave comments on posts. But if you want to give some feedback or have some questions you can contact in other ways.

©2019–2021 Severin Kaderli