Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Post History
This is my solution to the first task of the Advent of Code 2023. The task description is: On each line, the calibration value can be found by combining the first digit and the last digit (in t...
Question
rust
#1: Initial revision
Parsing numbers from a text file
This is my solution to the first task of the [Advent of Code 2023](https://adventofcode.com/2023). The task description is: > 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, which provides the correct sum (at least I passed the task): ```rust use std::fs::read_to_string; use regex::Regex; fn main() { let re = Regex::new(r"^[\D]*(\d)(|.*(\d))\D*$").unwrap(); let mut sum: u32 = 0; for line in read_to_string("calibration_data.txt").unwrap().lines() { println!("{line}"); let Some(caps) = re.captures(line) else { panic!("no match! in line {line}"); }; let first: &str = &caps.get(1).map_or("0", |m| m.as_str()); let second: &str = &caps.get(3).map_or(first, |m| m.as_str()); let mut compound: String = String::new(); compound.push_str(first); compound.push_str(second); println!("{first} + {second} = {compound}"); let compound: u32 = compound.parse().unwrap(); sum += compound; } println!("***********************"); println!("Calibration sum: {sum}"); println!("***********************"); } ``` Is there any way I could have done this better, especially regarding the extraction of the numbers from the text lines?