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)]
use aoc23::read;
use chumsky::prelude::*;
use chumsky::text::int;
use chumsky::{prelude::*, text::int};
enum Color {
Red,
@ -28,24 +27,28 @@ struct Hand {
impl Hand {
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)>| {
let mut red = None;
let mut green = None;
let mut blue = None;
for (amount, color) in colors {
let amount: u32 = amount.parse().unwrap();
match color {
Color::Red => red = Some(amount),
Color::Green => green = Some(amount),
Color::Blue => blue = Some(amount)
int(10)
.then_ignore(just(" "))
.then(Color::parser())
.separated_by(just(", "))
.map(|colors: Vec<(String, Color)>| {
let mut red = None;
let mut green = None;
let mut blue = None;
for (amount, color) in colors {
let amount: u32 = amount.parse().unwrap();
match color {
Color::Red => red = Some(amount),
Color::Green => green = Some(amount),
Color::Blue => blue = Some(amount)
}
}
}
Self {
red: red.unwrap_or_default(),
green: green.unwrap_or_default(),
blue: blue.unwrap_or_default()
}
})
Self {
red: red.unwrap_or_default(),
green: green.unwrap_or_default(),
blue: blue.unwrap_or_default()
}
})
}
}
@ -56,18 +59,22 @@ struct Game {
impl Game {
fn parser() -> impl Parser<char, Self, Error = Simple<char>> {
just("Game ").ignore_then(int(10)).then_ignore(just(": ")).then(Hand::parser().separated_by(just("; ")))
.map(|(game_id, hands)| {
Game {
id: game_id.parse().unwrap(),
hands
}
just("Game ")
.ignore_then(int(10))
.then_ignore(just(": "))
.then(Hand::parser().separated_by(just("; ")))
.map(|(game_id, hands)| Game {
id: game_id.parse().unwrap(),
hands
})
}
}
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<()> {
@ -77,8 +84,8 @@ fn main() -> anyhow::Result<()> {
let max_green = 13;
let max_blue = 14;
let mut id_sum = 0;
'game: for game in games {
for hand in game.hands {
'game: for game in &games {
for hand in &game.hands {
if hand.red > max_red || hand.green > max_green || hand.blue > max_blue {
continue 'game;
}
@ -87,5 +94,14 @@ fn main() -> anyhow::Result<()> {
}
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(())
}