81 lines
1.8 KiB
Rust
81 lines
1.8 KiB
Rust
use std::fs::File;
|
|
use std::io::{self, BufRead};
|
|
use std::path::Path;
|
|
use std::collections::HashMap;
|
|
|
|
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 {
|
|
//println!(
|
|
// "{} yields {:?} + {:?}",
|
|
// text,
|
|
// first_digit(&text),
|
|
// last_digit(&text),
|
|
//);
|
|
sum = sum + first_digit(&text).unwrap_or(0);
|
|
mus = mus + last_digit(&text).unwrap_or(0);
|
|
} else {
|
|
println!("Error on line \"{:?}\"", line);
|
|
}
|
|
}
|
|
}
|
|
|
|
println!("{}", 10*sum + mus);
|
|
}
|
|
|
|
const DIGITSTABLE: [(&str, u32); 18]= [
|
|
("1", 1), ("one", 1),
|
|
("2", 2), ("two", 2),
|
|
("3", 3), ("three", 3),
|
|
("4", 4), ("four", 4),
|
|
("5", 5), ("five", 5),
|
|
("6", 6), ("six", 6),
|
|
("7", 7), ("seven", 7),
|
|
("8", 8), ("eight", 8),
|
|
("9", 9), ("nine", 9),
|
|
];
|
|
|
|
fn first_digit(text: &String) -> Option<u32> {
|
|
let digits = HashMap::from(DIGITSTABLE);
|
|
|
|
let mut hit = false;
|
|
let mut first_digit: &u32 = &0;
|
|
let mut first_index: usize = 0;
|
|
for (needle, digit) in &digits {
|
|
let index = text.find(needle);
|
|
if index.is_some() && (!hit || index.unwrap() < first_index) {
|
|
hit = true;
|
|
first_digit = digit;
|
|
first_index = index.unwrap();
|
|
}
|
|
}
|
|
if hit { Some(*first_digit) } else { None }
|
|
}
|
|
|
|
fn last_digit(text: &String) -> Option<u32> {
|
|
let digits = HashMap::from(DIGITSTABLE);
|
|
|
|
let mut hit = false;
|
|
let mut last_digit: &u32 = &0;
|
|
let mut last_index: usize = 0;
|
|
for (needle, digit) in &digits {
|
|
let index = text.rfind(needle);
|
|
if index.is_some() && (!hit || index.unwrap() > last_index) {
|
|
hit = true;
|
|
last_digit = digit;
|
|
last_index = index.unwrap();
|
|
}
|
|
}
|
|
if hit { Some(*last_digit) } else { None }
|
|
}
|
|
|
|
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())
|
|
}
|