Rust Day 2 Part 1 optimize with early return

This commit is contained in:
Tobias Berger 2023-12-02 14:12:56 +01:00
parent 1feb4fae9f
commit b9fbda8085
Signed by: toby
GPG key ID: 2D05EFAB764D6A88

View file

@ -1,5 +1,11 @@
use crate::CubeCounts;
impl CubeCounts {
const fn exceeds_limits(&self) -> bool {
self.red > 12 || self.green > 13 || self.blue > 14
}
}
pub(crate) fn part_1(input: &'static str) -> usize {
let id_sum = input
.lines()
@ -11,8 +17,7 @@ pub(crate) fn part_1(input: &'static str) -> usize {
let groups = game.split("; ");
let game_counts = groups
.map(|group| {
for group in groups {
let color_counts = group.split(", ");
let group_counts = color_counts.map(|color_count| {
@ -31,19 +36,11 @@ pub(crate) fn part_1(input: &'static str) -> usize {
_ => unreachable!(),
}
});
group_counts.sum::<CubeCounts>()
})
.reduce(|acc, cube_count| CubeCounts {
red: u16::max(acc.red, cube_count.red),
green: u16::max(acc.green, cube_count.green),
blue: u16::max(acc.blue, cube_count.blue),
})
.expect("At least one group should exist in each game");
if game_counts.red <= 12 && game_counts.green <= 13 && game_counts.blue <= 14 {
Some(game_id + 1)
} else {
None
if group_counts.sum::<CubeCounts>().exceeds_limits() {
return None;
}
}
Some(game_id + 1)
})
.sum();
id_sum