[Rust] Advent of code day 1

Do Tran
4 min readDec 22, 2022

--

Introduction

Today, i came across the Advent of code 2022 which is a new thing to me. Hence, i want to give it a try using Rust to solve these problems. If you are interested, let’s try to solve these problems with me 😉.

Problem

Problem: Briefly, we have a bunch of elf carrying food, each of them has a bunch of food which contains various amount of calories. We need to find the elf who carries the most calories. The input of the program is a text file contains all the food carried by the elves and they are separated by a blank line for each elf. For example, if the text goes like this: 1 2 3 blank line 4 5 then we have [1,2,3] [4,5]. The output is to find the max number of calories carried by an elf (in our above example, it’s 9).

Part 1

Let’s get started.

First, we need to represent an elf and the total of calories it carries. We also derive Debug trait to make it easier for debugging.

Elf struct

Next, we need to read the file content into a String, you can find the file here, from that string we will split it by blank lines into chunks of text.

Reading file content from file path

One interesting point here is the function’s parameter is P: AsRef<Path>. It means that anything implement AsRef<Path> could be passed into the function, we can use str here because the trait is implemented for str by default.

str already implemented AsRef<Path>

Do you notice that output of the above function is the input of the below function? we kinda chains these function calls here.

Splitting the file content into chunks

In order to parse a &str into Elf, we can write a separate function for doing so but we have From trait and it does exactly the same thing.

Parsing a &str into Elf

Now we got almost everything we needed, Vec<&str> -> Vec<Elf>. The only thing left is to sort Vec<Elf> in descending order and take the first Elf.

Do we need to write a sort function ourselves? The answer is No. Rust also got us covered as it has got the Ordtrait.

Ord trait

We can use #[derive] macro in this case because Elf struct is just a thin wrapper for an i32.

Derive more trait for our struct

Notice that we derive 4 more trait and not just only Ord, why? If you look at the definition of Ord again, it requires out type must also implement Eq and PartialOrd as well. Nevertheless, Eq requires our type to implement PartialEq. By the way, It’s called Trait bound. That’s why need 4 instead of one.

We’ve got everything in the right place, let’s implement the main function.

main function

When we run the program, it gives us the answer
Elf(71924)

Part 2

The part 2 is almost the same as part 1. The difference here is instead of getting the max value, we get sum of the 3 biggest value. We only need to twist our main function a bit to get the desired result.

main function of part 2

You can find the source code here

--

--

Do Tran

Rust & C# Developer, blogger and trying to be a entrepreneur