95 lines
2.4 KiB
Rust
95 lines
2.4 KiB
Rust
use super::dayxx::Solution;
|
|
use std::str::FromStr;
|
|
use fancy_regex::Regex;
|
|
use strum_macros::EnumString;
|
|
|
|
#[allow(non_camel_case_types)]
|
|
#[derive(EnumString)]
|
|
enum WrittenNumbers {
|
|
zero = 0,
|
|
one = 1,
|
|
two = 2,
|
|
three = 3,
|
|
four = 4,
|
|
five = 5,
|
|
six = 6,
|
|
seven = 7,
|
|
eight = 8,
|
|
nine = 9
|
|
}
|
|
|
|
pub struct Day01 {}
|
|
|
|
impl Solution for Day01 {
|
|
fn part1(
|
|
&self,
|
|
input: &mut Vec<String>,
|
|
) -> Result<Box<dyn std::fmt::Display>, Box<dyn std::error::Error>> {
|
|
const REG: &str = r#"[0-9]"#;
|
|
let mut total: u32 = 0;
|
|
for line in input {
|
|
total += self.regex_get_num(REG, line);
|
|
}
|
|
|
|
Ok(Box::new(total))
|
|
}
|
|
|
|
fn part2(
|
|
&self,
|
|
input: &mut Vec<String>,
|
|
) -> Result<Box<dyn std::fmt::Display>, Box<dyn std::error::Error>> {
|
|
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);
|
|
}
|
|
|
|
Ok(Box::new(total))
|
|
}
|
|
|
|
fn get_day(&self) -> u8 {
|
|
1
|
|
}
|
|
}
|
|
|
|
impl Day01 {
|
|
fn regex_get_num(&self, regex: &str, input: &mut String) -> u32 {
|
|
let re = Regex::new(regex).unwrap();
|
|
|
|
let input = input.replace("oneight", "oneeight");
|
|
let input = input.replace("threeight", "threeeight");
|
|
let input = input.replace("fiveight", "fiveeight");
|
|
let input = input.replace("nineight", "nineeight");
|
|
let input = input.replace("twone", "twoone");
|
|
let input = input.replace("sevenine", "sevennine");
|
|
let input = input.replace("eightwo", "eighttwo");
|
|
|
|
// Get all single digits out of string
|
|
let matches: Vec<&str> = re
|
|
.find_iter(&input)
|
|
.map(|m| m.unwrap().as_str())
|
|
.collect();
|
|
|
|
// Convert everything to a number
|
|
let mut nums: Vec<u32> = vec![];
|
|
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))
|
|
}
|
|
}
|
|
|
|
let mut num: u32 = nums.first().unwrap_or(&0) * 10;
|
|
num += nums.last().unwrap_or(&0);
|
|
|
|
num
|
|
}
|
|
|
|
fn convert_written_number(number_str: &str) -> Option<u32> {
|
|
match WrittenNumbers::from_str(number_str) {
|
|
Ok(number) => Some(number as u32),
|
|
Err(_) => None,
|
|
}
|
|
}
|
|
}
|