Advent of Code 2022, Day 01 in Rust
December 01, 2022
It's that time of the year again! December has started, and once again, another Advent of Code starts! For this year, I'll attempt to solve the puzzles on the days they are released, with solutions written mainly in Rust. For some puzzles, I shall try to up the ante by writing a solution in Game Boy-flavored C.
Setting up my setup environment
I will be generating my code repository using fspoettel's advent-of-code-rust. This is a very neat repository template that has all the features you will need for Advent of Code: day scaffolding, built-in unit tests, input downloading, etc. It is very easy to setup and helps you with organizing your AoC codebase.
After generating my repository from the template, my personal preferences are to enable Clippy and the automated README.md
progress tracker. Then, I will clone the repository, and cargo scaffold 01
to prepare the files for the first day. With all that set up, time to proceed with the actual solving!
Solving the first part
I will be quoting each day's question statement, minus the flavor text. The first part is given as below:
The jungle must be too overgrown and difficult to navigate in vehicles or access from the air; the Elves' expedition traditionally goes on foot. As your boats approach land, the Elves begin taking inventory of their supplies. One important consideration is food - in particular, the number of Calories each Elf is carrying (your puzzle input).
The Elves take turns writing down the number of Calories contained by the various meals, snacks, rations, etc. that they've brought with them, one item per line. Each Elf separates their own inventory from the previous Elf's inventory (if any) by a blank line.
For example, suppose the Elves finish writing their items' Calories and end up with the following list:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 1000 2000 3000 4000 5000 6000 7000 8000 9000 10000This list represents the Calories of the food carried by five Elves:
The first Elf is carrying food with
1000
,2000
, and3000
Calories, a total of6000
Calories.The second Elf is carrying one food item with
4000
Calories.The third Elf is carrying food with
5000
and6000
Calories, a total of11000
Calories.The fourth Elf is carrying food with
7000
,8000
, and9000
Calories, a total of24000
Calories.The fifth Elf is carrying one food item with
10000
Calories.In case the Elves get hungry and need extra snacks, they need to know which Elf to ask: they'd like to know how many Calories are being carried by the Elf carrying the most Calories. In the example above, this is
24000
(carried by the fourth Elf). Find the Elf carrying the most Calories. How many total Calories is that Elf carrying?
This question is a rather simple one. As each chunk, seperated by an empty line, represents a single Elf, I will split the input text into each chunk, and push each chunk into a Vec
. An empty Vec
will also be created to hold the Calories count of each Elf (this will be empty because we will take care of this part later!)
1
2
let elves: Vec<&str> = input.split("\n\n").collect();
let mut foods: Vec<u32> = vec![];
Afterwards, I will iterate through each Elf inside the elves
vector, parse each of the &str
line to obtain its value, and sum all those values up to get the total Calories count of an Elf. I will then push this value into the foods
vector created above.
1
2
3
4
for elf in elves {
let food: u32 = elf.lines().map(|x| x.parse::<u32>().unwrap()).sum();
foods.push(food);
}
After dealing with this, it's just a matter of using a few Rust methods, namely .into_iter()
and .max()
to obtain the maximum amount of Calories carried.
1
Some(foods.into_iter().max().unwrap() as u32)
The Some
and the u32
cast was used here as the return type of the functions as scaffolded by advent-of-code-rust
is Option<u32>
by default.
I will be editing the test case result in the test_part_one()
function into 24000
as given in the question statement as well.
1
2
3
4
5
#[test]
fn test_part_one() {
let input = advent_of_code::read_file("examples", 1);
assert_eq!(part_one(input), Some(24000));
}
Solving the second part
The second part's question statement is given as such:
By the time you calculate the answer to the Elves' question, they've already realized that the Elf carrying the most Calories of food might eventually run out of snacks.
To avoid this unacceptable situation, the Elves would instead like to know the total Calories carried by the top three Elves carrying the most Calories. That way, even if one of those Elves runs out of snacks, they still have two backups.
In the example above, the top three Elves are the fourth Elf (with
24000
Calories), then the third Elf (with11000
Calories), then the fifth Elf (with10000
Calories). The sum of the Calories carried by these three elves is45000
.Find the top three Elves carrying the most Calories. How many Calories are those Elves carrying in total?
We will be going through the same steps as the previous part: Splitting text input into chunks, pushing them into a vector, calculating the total Calories count for each Elf.
1
2
3
4
5
6
let elves: Vec<&str> = input.split("\n\n").collect();
let mut foods: Vec<u32> = vec![];
for elf in elves {
let food: u32 = elf.lines().map(|x| x.parse::<u32>().unwrap()).sum();
foods.push(food);
}
For the next step, I'll be using Rust's built-in .sort_by()
method to sort the foods
vector in descending order.
1
foods.sort_by(|a, b| b.cmp(a));
After that, it's just a matter of grabbing the sum of the first 3 elements of the above vector.
1
Some(foods[0] + foods[1] + foods[2])
Similar to the previous part's test case, I'll be editing its result to 45000
as given by the question statement.
1
2
3
4
5
#[test]
fn test_part_two() {
let input = advent_of_code::read_file("examples", 2);
assert_eq!(part_two(&input), Some(45000));
}
Afterword
As typical for all day 1 questions of each year, this is a rather simple and straightforward question that can basically be solved using some parsing. The harder part of this is to write clean and Rust-y code I guess? I feel like I can definitely make the for
loops more Rust-y by using iterator methods more, but I still haven't figured it out yet!
My code can be found on my GitHub. Feel free to check it out!