Advent of Code Day 1 in Rust
Solving Advent of Code Day One

Hey again! It’s that time of the year when Advent of Code is upon us. If you aren’t aware of Advent of Code, it’s a series of challenges that run from the 1st of December to the 25th. It’s a delightful way to tackle programming challenges in an advent-themed manner.
This year, I’ve decided to take on most of the challenges using Rust. It’s an exciting opportunity for me to put Rust into practice and deepen my understanding of the language.
If you’re curious, you can check it out here. Let’s dive into the first challenge of Day 1, Part 1 of Advent of Code!
Rust Pun
I told a joke about lifetimes in Rust, but it hasn’t finished borrowing laughs yet
Day 1: Trebuchet?
Something is wrong with global snow production, and you’ve been selected to take a look. The Elves have even given you a map; on it, they’ve used stars to mark the top fifty locations that are likely to be having problems.
You’ve been doing this long enough to know that to restore snow operations, you need to check all fifty stars by December 25th.
Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck!
You try to ask why they can’t just use a weather machine (“not powerful enough”) and where they’re even sending you (“the sky”) and why your map looks mostly blank (“you sure ask a lot of questions”) and hang on did you just say the sky (“of course, where do you think snow comes from”) when you realize that the Elves are already loading you into a trebuchet (“please hold still, we need to strap you in”).
As they’re making the final adjustments, they discover that their calibration document (your puzzle input) has been amended by a very young Elf who was apparently just excited to show off her art skills. Consequently, the Elves are having trouble reading the values on the document.
The newly-improved calibration document consists of lines of text; each line originally contained a specific calibration value that the Elves now need to recover. On each line, the calibration value can be found by combining the first digit and the last digit (in that order) to form a single two-digit number.
For example:
1abc2
pqr3stu8vwx
a1b2c3d4e5f
treb7uchetIn this example, the calibration values of these four lines are 12, 38, 15, and 77. Adding these together produces 142.
Consider your entire calibration document. What is the sum of all of the calibration values?
Here is my solution to the challenge. I’m still relatively new to Rust, so feedback is welcome!
use std::fs;
use std::path::Path;
fn first_last(text: String) -> String {
let mut first: Option<String> = None;
let mut last: Option<String> = None;
for char in text.chars() {
if char.is_numeric() {
if first.is_none() {
first = Some(char.to_string());
}
last = Some(char.to_string());
}
}
let mut first_last_num = String::new();
if let Some(num) = first {
first_last_num.push_str(&num);
}
if let Some(num) = last {
first_last_num.push_str(&num);
}
first_last_num
}
fn main() {
let text_file = Path::new("./input.txt");
let file_content = fs::read_to_string(text_file).expect("Error reading file content");
let mut calibration_values = 0;
for line in file_content.lines() {
calibration_values += first_last(line.to_string()).parse::<i32>().unwrap();
}
println!("{:?}", calibration_values);
}My Solution Walkthrough
My approach begins by dynamically reading the file name provided by Advent of Code for the test case. It’s important to note that this file name can vary depending on the user. Once the file is identified, its content is read line by line.
In the provided code snippet, the file is opened using the given path, and its content is read into a string:
let text_file = Path::new("./input.txt");
let file_content = fs::read_to_string(text_file).expect("Error reading file content");Each line of the file contains a string that may include numeric characters. To handle this, two variables, first and last, are initialized with a None value. These variables represent the first and last numeric characters in the string. We will iterate over the string, checking each character’s numeric status using the is_numeric function.
for char in text.chars() {
if char.is_numeric() {
if first.is_none() {
first = Some(char.to_string());
}
last = Some(char.to_string());
}
}During the iteration, if the first variable is still None, it means the first number hasn’t been found, and it’s initialized with the current numeric character. Subsequent numeric characters become the last number until the iteration completes.
Following the iteration, we will do a check if there are values in the first and last variables using the if let Some construct:
let mut first_last_num = String::new();
if let Some(num) = first {
first_last_num.push_str(&num);
}
if let Some(num) = last {
first_last_num.push_str(&num);
}If values are present, they are appended to the first_last_num string. Finally, the content of this string is returned.
We will repeat the process for all the lines in the given input file, with the parsed integers accumulated to calculate the final result:
let text_file = Path::new("./input.txt");
let file_content = fs::read_to_string(text_file).expect("Error reading file content");
let mut calibration_values = 0;
for line in file_content.lines() {
calibration_values += first_last(line.to_string()).parse::<i32>().unwrap();
}
println!("{:?}", calibration_values);While this solution works, there might be opportunities to enhance its idiomatic nature. I welcome your insights and suggestions for improvements.
Before You Go
I would greatly appreciate it if you could share this piece with others. Please consider following the publication, and if you have any ideas to contribute to our growing Rust community, your input is more than welcome.
Check out Writing for Rustaceans Thank you.
More Reads
Rustaceans 🚀
Thank you for being a part of the Rustaceans community! Before you go:
- Show your appreciation with a clap and follow the publication
- Discover how you can contribute your own insights to Rustaceans.
- Connect with us: X | Weekly Rust Newsletter






