use std::{path::Path, vec}; use crate::{input::read_into_vec, error::AdventError}; fn process(lines: Vec::) -> Result { let calibrations: Vec = lines.iter().map(|v| { let first_digit = v.as_bytes() .iter() .skip_while(|i| { **i < 48u8 || **i > 57u8 }) .take(1).collect::>()[0]; let last_digit = v.as_bytes() .iter() .rev() .skip_while(|i| { **i < 48u8 || **i > 57u8 }) .take(1).collect::>()[0]; (*first_digit - 48) as u32 * 10 + (*last_digit - 48) as u32 }).collect(); Ok(calibrations.iter().sum::()) } pub fn one() -> Result { let lines: Vec = read_into_vec::(Path::new("resources/input1.txt"))?; Ok(process(lines)?) } struct Mutation(usize, char); struct Pattern(&'static str, char); pub fn two() -> Result { let mut lines = read_into_vec(Path::new("resources/input1.txt"))?; let mut mutations = Vec::::new(); mutations.reserve(10); let new_lines: Vec = lines.iter_mut().map(|str: &mut String| { let patterns = vec![ Pattern("one", '1'), Pattern("two", '2'), Pattern("three", '3'), Pattern("four", '4'), Pattern("five", '5'), Pattern("six", '6'), Pattern("seven", '7'), Pattern("eight", '8'), Pattern("nine", '9') ]; for pattern in patterns.iter() { let indices = str.match_indices(&pattern.0); indices.into_iter().for_each(|index| { mutations.push(Mutation(index.0, pattern.1)); mutations.push(Mutation(index.0 + pattern.0.len(), pattern.1)) }); } mutations.sort_by(|l, r| l.0.cmp(&r.0)); let mut offset = 0; for mutation in mutations.iter() { str.insert(mutation.0 + offset, mutation.1); offset += 1; } mutations.clear(); str.to_owned() }).collect(); Ok(process(new_lines)?) }