Cleaned up Day 1

This commit is contained in:
Luke Else 2023-12-01 11:25:59 +00:00
parent 3ff45cae13
commit acb8170222

View File

@ -28,7 +28,7 @@ impl Solution for Day01 {
const REG: &str = r#"[0-9]"#;
let mut total: u32 = 0;
for line in input {
total += self.regex_get_num(REG, line);
total += self.regex_get_num(REG, line)?;
}
Ok(Box::new(total))
@ -41,7 +41,7 @@ impl Solution for Day01 {
const REG: &str = r#"[0-9]|one|two|three|four|five|six|seven|eight|nine"#;
let mut total: u32 = 0;
for line in input {
total += self.regex_get_num(REG, line);
total += self.regex_get_num(REG, line)?;
}
Ok(Box::new(total))
@ -53,9 +53,10 @@ impl Solution for Day01 {
}
impl Day01 {
fn regex_get_num(&self, regex: &str, input: &mut String) -> u32 {
fn regex_get_num(&self, regex: &str, input: &mut String) -> Result<u32, Box<dyn std::error::Error>> {
let re = Regex::new(regex).unwrap();
// Really don't like this :(
let input = input.replace("oneight", "oneeight");
let input = input.replace("threeight", "threeeight");
let input = input.replace("fiveight", "fiveeight");
@ -75,14 +76,15 @@ impl Day01 {
for m in matches.clone() {
match Day01::convert_written_number(m) {
Some(n) => nums.push(n),
None => nums.push(m.parse::<u32>().unwrap_or(0))
None => nums.push(m.parse::<u32>()?)
}
}
// First number represents the tens, second represents the ones
let mut num: u32 = nums.first().unwrap_or(&0) * 10;
num += nums.last().unwrap_or(&0);
num
Ok(num)
}
fn convert_written_number(number_str: &str) -> Option<u32> {