Day 1 Part 2... Feeling in agony as I can't seem to use regex to save my life. Lookahead current does not work :(
This commit is contained in:
@ -1,7 +1,22 @@
|
||||
use super::dayxx::Solution;
|
||||
use regex::Regex;
|
||||
use std::str::FromStr;
|
||||
use fancy_regex::Regex;
|
||||
use strum_macros::EnumString;
|
||||
|
||||
const REG: &str = r#"[0-9]"#;
|
||||
#[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 {}
|
||||
|
||||
@ -10,9 +25,10 @@ impl Solution for Day01 {
|
||||
&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(line);
|
||||
total += self.regex_get_num(REG, line);
|
||||
}
|
||||
|
||||
Ok(Box::new(total))
|
||||
@ -22,7 +38,13 @@ impl Solution for Day01 {
|
||||
&self,
|
||||
input: &mut Vec<String>,
|
||||
) -> Result<Box<dyn std::fmt::Display>, Box<dyn std::error::Error>> {
|
||||
Ok(Box::new(0))
|
||||
const REG: &str = r#"(?=(\d|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 {
|
||||
@ -31,18 +53,34 @@ impl Solution for Day01 {
|
||||
}
|
||||
|
||||
impl Day01 {
|
||||
fn regex_get_num(&self, input: &mut String) -> u32 {
|
||||
let re = Regex::new(REG).unwrap();
|
||||
fn regex_get_num(&self, regex: &str, input: &mut String) -> u32 {
|
||||
let re = Regex::new(regex).unwrap();
|
||||
|
||||
// Get all single digits out of string
|
||||
let matches: Vec<u32> = re
|
||||
let matches: Vec<&str> = re
|
||||
.find_iter(input)
|
||||
.map(|m| m.as_str().parse::<u32>().unwrap_or_default())
|
||||
.map(|m| m.unwrap().as_str())
|
||||
.collect();
|
||||
|
||||
let mut num: u32 = matches.first().unwrap_or(&0) * 10;
|
||||
num += matches.last().unwrap_or(&0);
|
||||
// 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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user