Add src/01part2.rs

This commit is contained in:
Cassandra de la Cruz-Munoz 2023-12-05 21:34:35 +01:00
parent 2833e1dc93
commit 615e4b9c68

115
src/01part2.rs Normal file
View File

@ -0,0 +1,115 @@
use std::fs;
fn main() {
let file_path = "input/01input.txt";
let contents = fs::read_to_string(file_path).expect("should read file");
let lines = contents.lines();
let mut sum = 0;
for line in lines {
let mut line_chars = line.chars();
let mut line_chars_rev = line.chars().rev();
let mut left_found = false;
let mut right_found = false;
let mut left_num: u32 = 0;
let mut right_num: u32 = 0;
let mut left_chars: Vec<char> = Vec::new();
let mut right_chars: Vec<char> = Vec::new();
while !left_found || !right_found {
if !left_found {
left_chars.push(line_chars.next().unwrap());
if left_chars.last().unwrap().is_digit(10) {
left_num = left_chars.last().unwrap().to_digit(10).unwrap();
left_found = true;
} else {
left_num = num_from_word(&left_chars);
while left_num == 10 || left_num == 12 {
left_chars.remove(0);
left_num = num_from_word(&left_chars);
}
if left_num < 10 {
left_found = true;
}
}
}
if !right_found {
right_chars.insert(0, line_chars_rev.next().unwrap());
if right_chars.first().unwrap().is_digit(10) {
right_num = right_chars.first().unwrap().to_digit(10).unwrap();
right_found = true;
} else {
right_num = num_from_word(&right_chars);
while right_num == 10 || right_num == 11 {
right_chars.pop();
right_num = num_from_word(&right_chars);
}
if right_num < 10 {
right_found = true;
}
}
}
}
println!("{}{}", left_num, right_num);
sum += left_num * 10 + right_num;
}
println!("{}", sum);
}
fn num_from_word(word: &Vec<char>) -> u32 {
let transformed_word = word.into_iter().fold(String::new(), |w, c| {w.to_owned() + &c.to_string().to_string()});
match transformed_word.as_str() {
"one" => {return 1},
"o" => {return 13},
"on" => {return 11},
"ne" => {return 12},
"two" => {return 2},
"t" => {return 13},
"tw" => {return 11},
"wo" => {return 12},
"three" => {return 3},
"th" => {return 11},
"thr" => {return 11},
"thre" => {return 11},
"ee" => {return 12},
"ree" => {return 12},
"hree" => {return 12},
"four" => {return 4},
"f" => {return 11},
"fo" => {return 11},
"fou" => {return 11},
"r" => {return 12},
"ur" => {return 12},
"our" => {return 12},
"five" => {return 5},
"fi" => {return 11},
"fiv" => {return 11},
"ve" => {return 12},
"ive" => {return 12},
"six" => {return 6},
"s" => {return 11},
"si" => {return 11},
"ix" => {return 12},
"x" => {return 12},
"seven" => {return 7},
"se" => {return 11},
"sev" => {return 11},
"seve" => {return 11},
"en" => {return 12},
"ven" => {return 12},
"even" => {return 12},
"eight" => {return 8},
"e" => {return 13},
"ei" => {return 11},
"eig" => {return 11},
"eigh" => {return 11},
"ht" => {return 12},
"ght" => {return 12},
"ight" => {return 12},
"nine" => {return 9},
"n" => {return 13},
"ni" => {return 11},
"nin" => {return 11},
"ine" => {return 12},
"" => {return 13},
_ => {return 10},
};
}