day1
This commit is contained in:
47
2023/day1/src/main.rs
Normal file
47
2023/day1/src/main.rs
Normal file
@@ -0,0 +1,47 @@
|
||||
use std::fs::File;
|
||||
use std::io::{self, BufRead};
|
||||
use std::path::Path;
|
||||
|
||||
fn main() -> io::Result<()> {
|
||||
// File must exist in the current path
|
||||
let mut result = 0;
|
||||
if let Ok(lines) = read_lines("./src/input") {
|
||||
for line in lines.flatten() {
|
||||
if let Some(value) = extract_digit_pair_sum(&line) {
|
||||
println!("Current result: {} + {} = {}", result, value, result + value);
|
||||
result += value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
println!("Final result: {}", result);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Extracts first and last digits from a line, forms a number, and returns the sum
|
||||
fn extract_digit_pair_sum(line: &str) -> Option<i32> {
|
||||
let first_digit = get_first_digit(line)?;
|
||||
let last_digit = get_last_digit(line)?;
|
||||
|
||||
let digit_str = format!("{}{}", first_digit, last_digit);
|
||||
digit_str.parse::<i32>().ok()
|
||||
}
|
||||
|
||||
// Helper function to get the first digit in the string
|
||||
fn get_first_digit(s: &str) -> Option<char> {
|
||||
s.chars().find(|&c| c.is_digit(10))
|
||||
}
|
||||
|
||||
// Helper function to get the last digit in the string
|
||||
fn get_last_digit(s: &str) -> Option<char> {
|
||||
s.chars().rev().find(|&c| c.is_digit(10))
|
||||
}
|
||||
|
||||
// Returns an Iterator over the lines in the file
|
||||
fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
|
||||
where
|
||||
P: AsRef<Path>,
|
||||
{
|
||||
let file = File::open(filename)?;
|
||||
Ok(io::BufReader::new(file).lines())
|
||||
}
|
||||
Reference in New Issue
Block a user