Day 2 Part 2 Complete

This commit is contained in:
Luke Else 2023-12-02 11:48:22 +00:00
parent 2634f487e2
commit 13a891400a
2 changed files with 53 additions and 10 deletions

View File

@ -0,0 +1,5 @@
Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green
Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue
Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red
Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red
Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green

View File

@ -32,7 +32,35 @@ impl Solution for Day02 {
&self, &self,
input: &mut Vec<String>, input: &mut Vec<String>,
) -> Result<Box<dyn std::fmt::Display>, Box<dyn std::error::Error>> { ) -> Result<Box<dyn std::fmt::Display>, Box<dyn std::error::Error>> {
Ok(Box::new("Ready")) let mut power = 0u32;
for game in input.iter().enumerate() {
let mut min_count: HashMap<&str, u32> =
HashMap::from([("red", 0), ("green", 0), ("blue", 0)]);
let hands = game.1.split(';');
// Look at each time a handful is pulled out
for run in hands {
// Find the max number of instances of a given colour in a run
for colour in &mut min_count {
let num_cubes = self.get_num_cubes(run, colour.0)?;
if !num_cubes.is_empty() && num_cubes[0] > *colour.1 {
//Update with the new max
*colour.1 = num_cubes[0];
}
}
}
// Calculate the power for this given game
let mut game_power = 1u32;
for colour in &min_count {
game_power *= *colour.1;
}
// Combine to formt he total power
power += game_power;
}
Ok(Box::new(power))
} }
fn get_day(&self) -> u8 { fn get_day(&self) -> u8 {
@ -47,14 +75,9 @@ impl Day02 {
colour_max: &HashMap<&'static str, u32>, colour_max: &HashMap<&'static str, u32>,
) -> Result<bool, Box<dyn std::error::Error>> { ) -> Result<bool, Box<dyn std::error::Error>> {
for colour in colour_max { for colour in colour_max {
let re = Regex::new(format!("[0-9]+(?= {})", colour.0).as_str())?; let nums = self.get_num_cubes(input, colour.0)?;
for num in nums {
let nums_string: Vec<&str> = if num > *colour.1 {
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::<u32>()? > *colour.1 {
return Ok(false); return Ok(false);
} }
} }
@ -62,6 +85,21 @@ impl Day02 {
Ok(true) Ok(true)
} }
fn get_num_cubes(
&self,
input: &str,
colour: &str,
) -> Result<Vec<u32>, Box<dyn std::error::Error>> {
let re = Regex::new(format!("[0-9]+(?= {})", colour).as_str())?;
// Get the numbers correlating to a given colour and combine
let nums: Vec<u32> = re
.find_iter(&input)
.map(|c| c.unwrap().as_str().parse::<u32>().unwrap_or(0))
.collect();
Ok(nums)
}
} }
/// Test from puzzle input /// Test from puzzle input
@ -101,6 +139,6 @@ mod test {
.unwrap() .unwrap()
.to_string(); .to_string();
assert_eq!(answer, "Ready"); assert_eq!(answer, "2286");
} }
} }