Rust Day 4 Part 2

This commit is contained in:
Tobias Berger 2023-12-04 09:26:51 +01:00
parent 23255769b9
commit c166c644aa
Signed by: toby
GPG key ID: 2D05EFAB764D6A88
3 changed files with 70 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.4.1" version = "23.4.2"

View file

@ -1,6 +1,6 @@
[package] [package]
name = "advent-of-code" name = "advent-of-code"
version = "23.4.1" version = "23.4.2"
edition = "2021" edition = "2021"
default-run = "day04" default-run = "day04"

View file

@ -1,5 +1,69 @@
pub(crate) fn part_2(_input: &'static str) -> u64 { use std::collections::HashSet;
todo!("Part 2")
struct Card {
times_won: usize,
numbers: HashSet<u8>,
winning_numbers: HashSet<u8>,
}
impl Card {
fn winning_number_count(&self) -> usize {
HashSet::intersection(&self.numbers, &self.winning_numbers).count()
}
}
pub(crate) fn part_2(input: &'static str) -> usize {
let prefix_end = input.find(':').expect("Input should start with 'Card X:'") + 1;
let mut cards = input
.lines()
.map(|line| {
let mut number_groups = line[prefix_end..].split('|').map(|group| {
group
.split(' ')
.filter_map(|number| {
if number.is_empty() {
None
} else {
Some(
number
.trim()
.parse::<u8>()
.expect("Every number should be a valid u8"),
)
}
})
.collect()
});
let numbers = number_groups
.next()
.expect("There should be two groups of numbers");
let winning_numbers = number_groups
.next()
.expect("There should be two groups of numbers");
assert!(
number_groups.next().is_none(),
"There should be no more groups of numbers"
);
Card {
times_won: 1,
numbers,
winning_numbers,
}
})
.collect::<Vec<_>>();
for idx in 0..cards.len() {
let card_score = cards[idx].winning_number_count();
for winning_idx in (idx + 1)..(idx + 1 + card_score) {
cards[winning_idx].times_won += cards[idx].times_won;
}
}
cards.iter().map(|card| card.times_won).sum()
} }
#[cfg(test)] #[cfg(test)]
@ -8,17 +72,11 @@ mod tests {
#[test] #[test]
fn test_with_sample_solution() { fn test_with_sample_solution() {
assert_eq!( assert_eq!(super::part_2(SAMPLE_INPUT), 30);
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), 5659035);
super::part_2(crate::INPUT),
todo!("Add result for solved part 2")
);
} }
} }