Solution in Rust

This commit is contained in:
Andy Teijelo 2023-12-01 23:09:17 -05:00
parent 1d1277074b
commit cefc61f171

53
src/main.rs Normal file
View file

@ -0,0 +1,53 @@
use anyhow::Result;
use fancy_regex::Regex;
use std::{
collections::HashMap,
fs::File,
io::{BufRead, BufReader},
};
fn main() -> Result<()> {
let input = File::open("input.txt")?;
let reader = BufReader::new(input);
let patterns = Regex::new(
r#"on(?=e)|tw(?=o)|thre(?=e)|four|fiv(?=e)|six|seve(?=n)|eigh(?=t)|nin(?=e)|1|2|3|4|5|6|7|8|9"#,
)?;
let num_values = HashMap::from([
("on", "1"),
("tw", "2"),
("thre", "3"),
("four", "4"),
("fiv", "5"),
("six", "6"),
("seve", "7"),
("eigh", "8"),
("nin", "9"),
]);
let mut sum = 0;
for line in reader.lines() {
let line = line?;
let mut nums = vec![];
for m in patterns.find_iter(&line) {
let m = m?;
let text = m.as_str();
let v: &str = match num_values.get(text) {
Some(digit) => digit,
None => text,
};
nums.push(v);
}
let mut value = String::new();
value.push_str(nums.first().unwrap());
value.push_str(nums.last().unwrap());
sum += value.parse::<i32>().unwrap();
}
println!("{sum}");
Ok(())
}