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,39 +17,30 @@ pub(crate) fn part_1(input: &'static str) -> usize {
let groups = game.split("; ");
let game_counts = groups
.map(|group| {
let color_counts = group.split(", ");
for group in groups {
let color_counts = group.split(", ");
let group_counts = color_counts.map(|color_count| {
let (count, color) = color_count
.split_once(' ')
.expect("Every color count should have one space");
let group_counts = color_counts.map(|color_count| {
let (count, color) = color_count
.split_once(' ')
.expect("Every color count should have one space");
let count = count
.parse()
.expect("Every color count should be a valid number");
let count = count
.parse()
.expect("Every color count should be a valid number");
match color {
"red" => CubeCounts::red(count),
"green" => CubeCounts::green(count),
"blue" => CubeCounts::blue(count),
_ => 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
match color {
"red" => CubeCounts::red(count),
"green" => CubeCounts::green(count),
"blue" => CubeCounts::blue(count),
_ => unreachable!(),
}
});
if group_counts.sum::<CubeCounts>().exceeds_limits() {
return None;
}
}
Some(game_id + 1)
})
.sum();
id_sum