Advent of Code 2019 - Day 1

2 min read

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]