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