aoc day 2 finished, part 2 was almost easier than part 1

This commit is contained in:
2023-12-04 11:36:23 +01:00
parent 048c66102b
commit a671d0abaf
4 changed files with 246 additions and 0 deletions

View File

@@ -0,0 +1,132 @@
use nom::{
branch::alt,
bytes::complete::tag,
character::complete::{self, multispace1},
multi::separated_list1,
sequence::{pair, tuple},
IResult, Parser,
};
use std::cmp::max;
#[derive(Debug, Clone, Copy)]
enum Color {
Red,
Green,
Blue,
}
fn parse_input(input: &str) -> IResult<&str, Vec<(u32, Vec<(u32, u32, u32)>)>> {
let (input, result) = separated_list1(
multispace1,
tuple((
tag("Game "),
complete::u32,
tag(": "),
separated_list1(
tag("; "),
separated_list1(
tag(", "),
alt((
pair(complete::u32, tag(" red")).map(|(d, _)| (d, Color::Red)),
pair(complete::u32, tag(" green")).map(|(d, _)| (d, Color::Green)),
pair(complete::u32, tag(" blue")).map(|(d, _)| (d, Color::Blue)),
)),
)
.map(|list_of_colors_with_number| {
let mut r = (0, 0, 0);
for (number, color) in list_of_colors_with_number {
match color {
Color::Red => r.0 = number,
Color::Green => r.1 = number,
Color::Blue => r.2 = number,
}
}
r
}),
),
))
.map(|(_, iter, _, game_results)| (iter, game_results)),
)(input)?;
Ok((input, result))
}
fn solve_1(game_results: &[(u32, Vec<(u32, u32, u32)>)]) -> u32 {
let red_max = 12;
let green_max = 13;
let blue_max = 14;
game_results
.iter()
.filter(|(_, list_of_game_results)| {
list_of_game_results
.iter()
.all(|&(red, green, blue)| red <= red_max && green <= green_max && blue <= blue_max)
})
.map(|(iter, _)| iter)
.sum()
}
fn solve_2(game_results: &[(u32, Vec<(u32, u32, u32)>)]) -> u32 {
game_results
.iter()
.map(|(_, list_of_game_results)| {
let mut minima = (0, 0, 0);
for game_result in list_of_game_results {
minima.0 = max(minima.0, game_result.0);
minima.1 = max(minima.1, game_result.1);
minima.2 = max(minima.2, game_result.2);
}
minima.0 * minima.1 * minima.2
})
.sum()
}
fn main() {
println!("Hello, this is Patrick!");
let input_txt = include_str!("../input.txt");
let (_, game_results) = parse_input(input_txt).unwrap();
let result_1 = solve_1(&game_results[..]);
println!(
"The sum of the IDs of the games that were possible is {}",
result_1
);
let result_2 = solve_2(&game_results[..]);
println!(
"The sum of the power of of minimum of present sets is {}",
result_2
);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_1() {
let test_input = include_str!("../test_input.txt");
let (_, game_results) = parse_input(test_input).unwrap();
assert_eq!(solve_1(&game_results[..]), 8);
}
#[test]
fn test_2() {
let test_input = include_str!("../test_input.txt");
let (_, game_results) = parse_input(test_input).unwrap();
assert_eq!(solve_2(&game_results[..]), 2286);
}
}