Day 1 part 2.

This commit is contained in:
Drew Galbraith 2023-12-01 07:12:35 -08:00
parent 6b55dd0f52
commit c5e0ac820a
1 changed files with 92 additions and 2 deletions

View File

@ -1,6 +1,6 @@
use std::io; use std::io;
fn main() { fn get_calibration_digits() -> u32 {
let mut buffer = String::new(); let mut buffer = String::new();
let mut sum = 0; let mut sum = 0;
while io::stdin().read_line(&mut buffer).unwrap() > 0 { while io::stdin().read_line(&mut buffer).unwrap() > 0 {
@ -8,5 +8,95 @@ fn main() {
sum += nums.first().unwrap() * 10 + nums.last().unwrap(); sum += nums.first().unwrap() * 10 + nums.last().unwrap();
buffer = String::new(); buffer = String::new();
} }
println!("Sum: {}", sum); 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<usize> = 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()
}
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
}
fn main() {
println!("Sum: {}", get_calibration_digits_alnum());
} }