advent_of_code/2023/day1/rust/part_two.rs

43 lines
1.3 KiB
Rust
Raw Normal View History

use std::fs::File;
use std::io::{self, prelude::*, BufReader};
fn find_digit(line: String, match_array: &[&str]) -> u32 {
println!("{}", line);
for (i, item) in line.chars().enumerate(){
if item.is_numeric() {
return item as u32 - '0' as u32;
}
else {
for count in 0..match_array.len() {
if line[0..i+1].contains(match_array[count]) {
return count as u32;
}
}
}
}
return 0;
}
static texts: [&str; 10] = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"];
static rev_texts: [&str; 10] = ["orez", "eno", "owt", "eerht", "ruof", "evif", "xis", "neves", "thgie", "enin"];
fn process_line(line: String) -> u32 {
let first_digit: u32 = find_digit(line.clone(), &texts);
let last_digit: u32 = find_digit(line.chars().rev().collect::<String>().clone(), &rev_texts);
println!("{}{}", first_digit, last_digit);
return first_digit*10+last_digit;
}
fn main() -> io::Result<()> {
let mut sum: u32 = 0;
let file = File::open("../input.txt")?;
let reader = BufReader::new(file);
for line in reader.lines() {
sum = process_line(line?) + sum;
}
println!("{}", sum);
Ok(())
}