aoc2023/examples/day1_2.rs
2023-12-01 15:54:03 -05:00

44 lines
1.2 KiB
Rust

const WORDS: [&'static str; 10] = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"];
fn main() {
let mut total = 0;
for line in std::io::stdin().lines() {
let line = line.unwrap();
if line.len() == 0 { continue }
let mut c1 = line.len() - 1;
let mut c2 = 0;
let mut n1 = 0;
let mut n2 = 0;
for (i, word) in WORDS.iter().enumerate() {
if let Some(d1) = line.find(word) {
if d1 <= c1 {
c1 = d1;
n1 = i;
}
}
if let Some(d2) = line.rfind(word) {
if d2 >= c2 {
c2 = d2;
n2 = i;
}
}
}
for (i, word) in ('0'..='9').enumerate() {
if let Some(d1) = line.find(word) {
if d1 <= c1 {
c1 = d1;
n1 = i;
}
}
if let Some(d2) = line.rfind(word) {
if d2 >= c2 {
c2 = d2;
n2 = i;
}
}
}
total += n1*10 + n2;
}
println!("{}", total);
}