avatarJohn Philip

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

4885

Abstract

</span>() { first = <span class="hljs-title function_ invoke__">Some</span>(<span class="hljs-type">char</span>.<span class="hljs-title function_ invoke__">to_string</span>()); } last = <span class="hljs-title function_ invoke__">Some</span>(<span class="hljs-type">char</span>.<span class="hljs-title function_ invoke__">to_string</span>()); } }

<span class="hljs-keyword">let</span> <span class="hljs-keyword">mut </span><span class="hljs-variable">first_last_num</span> = <span class="hljs-type">String</span>::<span class="hljs-title function_ invoke__">new</span>();
<span class="hljs-keyword">if</span> <span class="hljs-keyword">let</span> <span class="hljs-variable">Some</span>(num) = first {
    first_last_num.<span class="hljs-title function_ invoke__">push_str</span>(&amp;num);
}

<span class="hljs-keyword">if</span> <span class="hljs-keyword">let</span> <span class="hljs-variable">Some</span>(num) = last {
    first_last_num.<span class="hljs-title function_ invoke__">push_str</span>(&amp;num);
}

first_last_num

} <span class="hljs-keyword">fn</span> <span class="hljs-title function_">main</span>() { <span class="hljs-keyword">let</span> <span class="hljs-variable">text_file</span> = Path::<span class="hljs-title function_ invoke__">new</span>(<span class="hljs-string">"./input.txt"</span>); <span class="hljs-keyword">let</span> <span class="hljs-variable">file_content</span> = fs::<span class="hljs-title function_ invoke__">read_to_string</span>(text_file).<span class="hljs-title function_ invoke__">expect</span>(<span class="hljs-string">"Error reading file content"</span>); <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut </span><span class="hljs-variable">calibration_values</span> = <span class="hljs-number">0</span>; <span class="hljs-keyword">for</span> <span class="hljs-variable">line</span> <span class="hljs-keyword">in</span> file_content.<span class="hljs-title function_ invoke__">lines</span>() { calibration_values += <span class="hljs-title function_ invoke__">first_last</span>(line.<span class="hljs-title function_ invoke__">to_string</span>()).parse::<<span class="hljs-type">i32</span>>().<span class="hljs-title function_ invoke__">unwrap</span>(); } <span class="hljs-built_in">println!</span>(<span class="hljs-string">"{:?}"</span>, calibration_values); }</pre></div><h2 id="c255">My Solution Walkthrough</h2><p id="f136">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.</p><p id="b716">In the provided code snippet, the file is opened using the given path, and its content is read into a string:</p><div id="9b8a"><pre><span class="hljs-keyword">let</span> <span class="hljs-variable">text_file</span> = Path::<span class="hljs-title function_ invoke__">new</span>(<span class="hljs-string">"./input.txt"</span>); <span class="hljs-keyword">let</span> <span class="hljs-variable">file_content</span> = fs::<span class="hljs-title function_ invoke__">read_to_string</span>(text_file).<span class="hljs-title function_ invoke__">expect</span>(<span class="hljs-string">"Error reading file content"</span>);</pre></div><p id="e837">Each line of the file contains a string that may include numeric characters. To handle this, two variables, <code>first</code> and <code>last</code>, are initialized with a <code>None</code> 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 <code>is_numeric</code> function.</p><div id="6eed"><pre> <span class="hljs-keyword">for</span> <span class="hljs-variable">char</span> <span class="hljs-keyword">in</span> text.<span class="hljs-title function_ invoke__">chars</span>() { <span class="hljs-keyword">if</span> <span class="hljs-type">char</span>.<span class="hljs-title function_ invoke__">is_numeric</span>() { <span class="hljs-keyword">if</span> first.<span class="hljs-title function_ invoke__">is_none</span>() { first = <span class="hljs-title function_ invoke__">Some</span>(<span class="hljs-type">char</span>.<span class="hljs-title function_ invoke__">to_string</span>()); } last = <span class="hljs-title function_ invoke__">Some</span>(<span class="hljs-type">char</span>.<span class="hljs-title function_ invoke__">to_string</span>()); } }</pre></div><p id="cd5d">During the iteration, if the <code>first</code> variable is still <code>None</code>, it means the first number hasn’t been found, and it’s initialized with the current numeric character

Options

. Subsequent numeric characters become the last number until the iteration completes.</p><p id="c07c">Following the iteration, we will do a check if there are values in the <code>first</code> and <code>last</code> variables using the <code>if let Some</code> construct:</p><div id="1cfe"><pre> <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut </span><span class="hljs-variable">first_last_num</span> = <span class="hljs-type">String</span>::<span class="hljs-title function_ invoke__">new</span>(); <span class="hljs-keyword">if</span> <span class="hljs-keyword">let</span> <span class="hljs-variable">Some</span>(num) = first { first_last_num.<span class="hljs-title function_ invoke__">push_str</span>(&num); }

<span class="hljs-keyword">if</span> <span class="hljs-keyword">let</span> <span class="hljs-variable">Some</span>(num) = last {
    first_last_num.<span class="hljs-title function_ invoke__">push_str</span>(&amp;num);
}</pre></div><p id="20b6">If values are present, they are appended to the <code>first_last_num</code> string. Finally, the content of this string is returned.</p><p id="b77c">We will repeat the process for all the lines in the given input file, with the parsed integers accumulated to calculate the final result:</p><div id="d711"><pre>    <span class="hljs-keyword">let</span> <span class="hljs-variable">text_file</span> = Path::<span class="hljs-title function_ invoke__">new</span>(<span class="hljs-string">"./input.txt"</span>);
<span class="hljs-keyword">let</span> <span class="hljs-variable">file_content</span> = fs::<span class="hljs-title function_ invoke__">read_to_string</span>(text_file).<span class="hljs-title function_ invoke__">expect</span>(<span class="hljs-string">"Error reading file content"</span>);
<span class="hljs-keyword">let</span> <span class="hljs-keyword">mut </span><span class="hljs-variable">calibration_values</span> = <span class="hljs-number">0</span>;
<span class="hljs-keyword">for</span> <span class="hljs-variable">line</span> <span class="hljs-keyword">in</span> file_content.<span class="hljs-title function_ invoke__">lines</span>() {
    calibration_values += <span class="hljs-title function_ invoke__">first_last</span>(line.<span class="hljs-title function_ invoke__">to_string</span>()).parse::&lt;<span class="hljs-type">i32</span>&gt;().<span class="hljs-title function_ invoke__">unwrap</span>();
}
<span class="hljs-built_in">println!</span>(<span class="hljs-string">"{:?}"</span>, calibration_values);</pre></div><p id="8ceb">While this solution works, there might be opportunities to enhance its idiomatic nature. I welcome your insights and suggestions for improvements.</p><h2 id="020d">Before You Go</h2><p id="b60b">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.</p><p id="0621">Check out <a href="https://readmedium.com/write-for-us-at-rustancean-121ed52eae"><b><i>Writing for Rustaceans</i></b></a> Thank you.</p><h2 id="ac8e">More Reads</h2><div id="eef4" class="link-block">
      <a href="https://readmedium.com/lifetimekata-lifetime-elision-67b6f0766e4c">
        <div>
          <div>
            <h2>Lifetimekata: _lifetime_elision</h2>
            <div><h3>Solution to exercise ex03 of lifetimekata</h3></div>
            <div><p>medium.com</p></div>
          </div>
          <div>
            <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*ZqLsdB37r8juaRhs1FaOSQ.jpeg)"></div>
          </div>
        </div>
      </a>
    </div><div id="56ae" class="link-block">
      <a href="https://readmedium.com/rust-challenge-anagram-75490656f8fd">
        <div>
          <div>
            <h2>Rust Challenge: Anagram</h2>
            <div><h3>Learning Rust Through Small Challenges</h3></div>
            <div><p>medium.com</p></div>
          </div>
          <div>
            <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*A0AZeFZHgWU88rSO)"></div>
          </div>
        </div>
      </a>
    </div><h2 id="6d53">Rustaceans 🚀</h2><p id="e6c3">Thank you for being a part of the Rustaceans community! Before you go:</p><ul><li>Show your appreciation with a clap and follow the publication</li><li>Discover how you can contribute your own insights to <a href="https://readmedium.com/write-for-us-at-rustancean-121ed52eae"><b><i>Rustaceans.</i></b></a></li><li>Connect with us: <a href="https://twitter.com/rustaceans_rs"><b><i>X</i></b></a> | <a href="https://substack.com/@weeklyrust"><b><i>Weekly Rust Newsletter</i></b></a></li></ul></article></body>

Advent of Code Day 1 in Rust

Solving Advent of Code Day One

Image by https://www.smarty.com/

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
treb7uchet

In 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:

Programming
Technology
Rustlang
Rust Programming Language
Software Development
Recommended from ReadMedium