use std::io; pub fn get_calibration_digits() -> u32 { let mut buffer = String::new(); let mut sum = 0; while io::stdin().read_line(&mut buffer).unwrap() > 0 { let nums: Vec = buffer.chars().filter_map(|c| c.to_digit(10)).collect(); sum += nums.first().unwrap() * 10 + nums.last().unwrap(); buffer = String::new(); } sum } const NUMBERS: [&'static str; 9] = [ "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", ]; enum SearchDir { First, Last, } fn get_digit(line: &String, dir: SearchDir) -> u32 { let mut first: usize = 0; let mut index: Option = None; for n in 1..=9 { let f = match &dir { SearchDir::First => line.find(&n.to_string()), SearchDir::Last => line.rfind(&n.to_string()), }; if f == None { continue; } let found = f.unwrap(); match index { None => { index = f; first = n; } Some(i) => match &dir { SearchDir::First => { if found < i { index = f; first = n; } } SearchDir::Last => { if found > i { index = f; first = n; } } }, } } for (num, num_str) in NUMBERS.iter().enumerate() { let f = match &dir { SearchDir::First => line.find(num_str), SearchDir::Last => line.rfind(num_str), }; if f == None { continue; } let found = f.unwrap(); match index { None => { index = f; first = num + 1; } Some(i) => match &dir { SearchDir::First => { if found < i { index = f; first = num + 1; } } SearchDir::Last => { if found > i { index = f; first = num + 1; } } }, } } first.try_into().unwrap() } pub fn get_calibration_digits_alnum() -> u32 { let mut buffer = String::new(); let mut sum = 0; while io::stdin().read_line(&mut buffer).unwrap() > 0 { let val = (get_digit(&buffer, SearchDir::First) * 10) + get_digit(&buffer, SearchDir::Last); sum += val; buffer = String::new(); } sum }