This commit is contained in:
simon
2024-09-13 08:44:45 +02:00
parent e946da828b
commit eada91d3b9
6 changed files with 1091 additions and 0 deletions

1000
2023/day1/src/input Normal file

File diff suppressed because it is too large Load Diff

47
2023/day1/src/main.rs Normal file
View 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())
}