day 2 part 1
This commit is contained in:
parent
21d44796c7
commit
0f1f290bd2
2 changed files with 191 additions and 0 deletions
91
src/bin/day2.rs
Normal file
91
src/bin/day2.rs
Normal file
|
@ -0,0 +1,91 @@
|
|||
#![forbid(elided_lifetimes_in_paths, unsafe_code)]
|
||||
|
||||
use aoc23::read;
|
||||
use chumsky::prelude::*;
|
||||
use chumsky::text::int;
|
||||
|
||||
enum Color {
|
||||
Red,
|
||||
Green,
|
||||
Blue
|
||||
}
|
||||
|
||||
impl Color {
|
||||
fn parser() -> impl Parser<char, Self, Error = Simple<char>> {
|
||||
choice((
|
||||
just("red").map(|_| Self::Red),
|
||||
just("green").map(|_| Self::Green),
|
||||
just("blue").map(|_| Self::Blue)
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
struct Hand {
|
||||
red: u32,
|
||||
green: u32,
|
||||
blue: u32
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
Self {
|
||||
red: red.unwrap_or_default(),
|
||||
green: green.unwrap_or_default(),
|
||||
blue: blue.unwrap_or_default()
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct Game {
|
||||
id: u32,
|
||||
hands: Vec<Hand>
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn parser() -> impl Parser<char, Vec<Game>, Error = Simple<char>> {
|
||||
Game::parser().then_ignore(just("\n")).repeated().then_ignore(end())
|
||||
}
|
||||
|
||||
fn main() -> anyhow::Result<()> {
|
||||
let games = read("inputs/day2.txt", parser())?;
|
||||
|
||||
let max_red = 12;
|
||||
let max_green = 13;
|
||||
let max_blue = 14;
|
||||
let mut id_sum = 0;
|
||||
'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;
|
||||
}
|
||||
}
|
||||
id_sum += game.id;
|
||||
}
|
||||
println!("{id_sum}");
|
||||
|
||||
Ok(())
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue