Rust Day 2 Part 2

This commit is contained in:
Tobias Berger 2023-12-02 13:29:02 +01:00
parent 4b8e2ab4cc
commit dd2b1d362c
Signed by: toby
GPG key ID: 2D05EFAB764D6A88
3 changed files with 87 additions and 12 deletions

2
rust/Cargo.lock generated
View file

@ -4,4 +4,4 @@ version = 3
[[package]] [[package]]
name = "advent-of-code" name = "advent-of-code"
version = "23.2.1" version = "23.2.2"

View file

@ -1,6 +1,6 @@
[package] [package]
name = "advent-of-code" name = "advent-of-code"
version = "23.2.1" version = "23.2.2"
edition = "2021" edition = "2021"
default-run = "day02" default-run = "day02"

View file

@ -1,5 +1,86 @@
pub(crate) fn part_2(_input: &'static str) -> u64 { #[derive(Default)]
todo!("Part 2") struct CubeCounts {
red: u16,
green: u16,
blue: u16,
}
impl CubeCounts {
const fn power(&self) -> u16 {
self.red * self.green * self.blue
}
}
impl std::ops::Add<CubeCounts> for CubeCounts {
type Output = Self;
fn add(self, rhs: CubeCounts) -> Self::Output {
Self {
red: self.red + rhs.red,
green: self.green + rhs.green,
blue: self.blue + rhs.blue,
}
}
}
impl std::iter::Sum<CubeCounts> for CubeCounts {
fn sum<I: Iterator<Item = CubeCounts>>(iter: I) -> Self {
iter.fold(CubeCounts::default(), |acc, x| acc + x)
}
}
pub(crate) fn part_2(input: &'static str) -> u16 {
let id_sum = input
.lines()
.map(|line| {
let game_start_index = line.find(":").expect("Every line should have a ': '") + 2;
let game = &line[game_start_index..];
let groups = game.split("; ");
let game_counts = groups
.map(|group| {
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 count = count.parse().expect(
format!("Every color count should be a valid number - `{count}` `{color}`")
.as_str(),
);
match color {
"red" => CubeCounts {
red: count,
..Default::default()
},
"green" => CubeCounts {
green: count,
..Default::default()
},
"blue" => CubeCounts {
blue: count,
..Default::default()
},
_ => 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");
game_counts.power()
})
.sum();
id_sum
} }
#[cfg(test)] #[cfg(test)]
@ -8,17 +89,11 @@ mod tests {
#[test] #[test]
fn test_with_sample_solution() { fn test_with_sample_solution() {
assert_eq!( assert_eq!(super::part_2(SAMPLE_INPUT), 2286);
super::part_2(SAMPLE_INPUT),
todo!("Add result from example part 2")
);
} }
#[test] #[test]
fn test_with_solution() { fn test_with_solution() {
assert_eq!( assert_eq!(super::part_2(crate::INPUT), 63981);
super::part_2(crate::INPUT),
todo!("Add result for solved part 2")
);
} }
} }