Files
adventofcode/2023/day/1/main.rs
Kees van Kempen ce39b976ab Initial commit: solve 2023 day 1
This is my very first piece of Rust code. When it compiled for the first
time, the result was what it should be, so I am happy :-).

It did take me > 1 hour to solve this...
2023-12-02 21:40:27 +01:00

42 lines
906 B
Rust

use std::fs::File;
use std::io::{self, BufRead};
use std::path::Path;
fn main() {
let mut sum = 0;
let mut mus = 0;
if let Ok(lines) = read_lines("./input") {
for line in lines {
if let Ok(text) = line {
sum = sum + first_digit(&text);
mus = mus + last_digit(&text);
}
}
}
println!("{}", 10*sum + mus);
}
// TODO: Switch to Option(i32) to allow not having a digit in text <https://doc.rust-lang.org/std/option/>.
fn first_digit(text: &String) -> i32 {
for c in text.chars() {
if c.is_digit(10) {
return c.to_digit(10).unwrap() as i32;
}
}
// TODO: What if there is no digit?
0
}
fn last_digit(text: &String) -> i32 {
let txet = &mut text.chars().rev().collect();
first_digit(txet)
}
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())
}