This is wrong, though, as cases like `oneight` should return `83` whereas I replace the `one`s first, so that `1ight` will remain that way. See <https://www.reddit.com/r/adventofcode/comments/1884fpl/2023_day_1for_those_who_stuck_on_part_2/>.
66 lines
1.5 KiB
Rust
66 lines
1.5 KiB
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 {
|
|
// TODO: Please us something like a collection instead of
|
|
// hardcoding every replacement.
|
|
let sanitext = text
|
|
.replace("one", "1")
|
|
.replace("two", "2")
|
|
.replace("three", "3")
|
|
.replace("four", "4")
|
|
.replace("five", "5")
|
|
.replace("six", "6")
|
|
.replace("seven", "7")
|
|
.replace("eight", "8")
|
|
.replace("nine", "9")
|
|
;
|
|
// DEBUG:
|
|
println!(
|
|
"{} => {} yields {} + {} = {}",
|
|
text,
|
|
sanitext,
|
|
first_digit(&sanitext),
|
|
last_digit(&sanitext),
|
|
first_digit(&sanitext) + last_digit(&sanitext)
|
|
);
|
|
sum = sum + first_digit(&sanitext);
|
|
mus = mus + last_digit(&sanitext);
|
|
} else {
|
|
println!("Error on line \"{:?}\"", line);
|
|
}
|
|
}
|
|
}
|
|
|
|
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())
|
|
}
|