day 2 part 2

This commit is contained in:
Dominic 2023-12-02 17:14:37 +01:00
parent 0f1f290bd2
commit 09be63205f
Signed by: msrd0
GPG key ID: DCC8C247452E98F9

View file

@ -1,8 +1,7 @@
#![forbid(elided_lifetimes_in_paths, unsafe_code)] #![forbid(elided_lifetimes_in_paths, unsafe_code)]
use aoc23::read; use aoc23::read;
use chumsky::prelude::*; use chumsky::{prelude::*, text::int};
use chumsky::text::int;
enum Color { enum Color {
Red, Red,
@ -28,7 +27,11 @@ struct Hand {
impl Hand { impl Hand {
fn parser() -> impl Parser<char, Self, Error = Simple<char>> { fn parser() -> impl Parser<char, Self, Error = Simple<char>> {
int(10).then_ignore(just(" ")).then(Color::parser()).separated_by(just(", ")).map(|colors: Vec<(String, Color)>| { int(10)
.then_ignore(just(" "))
.then(Color::parser())
.separated_by(just(", "))
.map(|colors: Vec<(String, Color)>| {
let mut red = None; let mut red = None;
let mut green = None; let mut green = None;
let mut blue = None; let mut blue = None;
@ -56,18 +59,22 @@ struct Game {
impl Game { impl Game {
fn parser() -> impl Parser<char, Self, Error = Simple<char>> { fn parser() -> impl Parser<char, Self, Error = Simple<char>> {
just("Game ").ignore_then(int(10)).then_ignore(just(": ")).then(Hand::parser().separated_by(just("; "))) just("Game ")
.map(|(game_id, hands)| { .ignore_then(int(10))
Game { .then_ignore(just(": "))
.then(Hand::parser().separated_by(just("; ")))
.map(|(game_id, hands)| Game {
id: game_id.parse().unwrap(), id: game_id.parse().unwrap(),
hands hands
}
}) })
} }
} }
fn parser() -> impl Parser<char, Vec<Game>, Error = Simple<char>> { fn parser() -> impl Parser<char, Vec<Game>, Error = Simple<char>> {
Game::parser().then_ignore(just("\n")).repeated().then_ignore(end()) Game::parser()
.then_ignore(just("\n"))
.repeated()
.then_ignore(end())
} }
fn main() -> anyhow::Result<()> { fn main() -> anyhow::Result<()> {
@ -77,8 +84,8 @@ fn main() -> anyhow::Result<()> {
let max_green = 13; let max_green = 13;
let max_blue = 14; let max_blue = 14;
let mut id_sum = 0; let mut id_sum = 0;
'game: for game in games { 'game: for game in &games {
for hand in game.hands { for hand in &game.hands {
if hand.red > max_red || hand.green > max_green || hand.blue > max_blue { if hand.red > max_red || hand.green > max_green || hand.blue > max_blue {
continue 'game; continue 'game;
} }
@ -87,5 +94,14 @@ fn main() -> anyhow::Result<()> {
} }
println!("{id_sum}"); println!("{id_sum}");
let mut power_sum = 0;
for game in &games {
let min_red = game.hands.iter().map(|h| h.red).max().unwrap_or_default();
let min_green = game.hands.iter().map(|h| h.green).max().unwrap_or_default();
let min_blue = game.hands.iter().map(|h| h.blue).max().unwrap_or_default();
power_sum += min_red * min_green * min_blue;
}
println!("{power_sum}");
Ok(()) Ok(())
} }