use std::collections::HashMap; use super::Solution; use fancy_regex::Regex; pub struct Day02 {} impl Solution for Day02 { fn part1( &self, input: &mut Vec, ) -> Result, Box> { // Read games // Parse into regex with colour to get the number of colours for each game // Create an is Game Valid function let colour_max: HashMap<&str, u32> = HashMap::from([("red", 12), ("green", 13), ("blue", 14)]); let mut ans = 0; for game in input.iter().enumerate() { if self.is_game_valid(game.1, &colour_max)? { ans += game.0 + 1 } } Ok(Box::new(ans)) } fn part2( &self, input: &mut Vec, ) -> Result, Box> { Ok(Box::new("Ready")) } fn get_day(&self) -> u8 { 2 } } impl Day02 { fn is_game_valid( &self, input: &str, colour_max: &HashMap<&'static str, u32>, ) -> Result> { for colour in colour_max { let re = Regex::new(format!("[0-9]+(?= {})", colour.0).as_str())?; let nums_string: Vec<&str> = re.find_iter(&input).map(|c| c.unwrap().as_str()).collect(); for num in nums_string { // If just 1 game is over, return false if num.parse::()? > *colour.1 { return Ok(false); } } } Ok(true) } } /// Test from puzzle input #[cfg(test)] mod test { use super::*; use crate::*; #[test] fn part1() { let challenge = day02::Day02 {}; //Complete the Challenge let answer = challenge .part1( get_input(challenge.get_day(), utils::InputType::Test1) .unwrap() .as_mut(), ) .unwrap() .to_string(); assert_eq!(answer, "8"); } #[test] fn part2() { let challenge = day02::Day02 {}; //Complete the Challenge let answer = challenge .part2( get_input(challenge.get_day(), utils::InputType::Test2) .unwrap() .as_mut(), ) .unwrap() .to_string(); assert_eq!(answer, "Ready"); } }