Simplified code for day 04

This commit is contained in:
Dreaded_X 2023-12-04 11:47:29 +01:00
parent 3720115175
commit 76e36d43c1
Signed by: Dreaded_X
GPG Key ID: 5A0CBFE3C3377FAA

View File

@ -91,10 +91,10 @@ impl aoc::Solver for Day {
} }
fn part2(input: &str) -> Self::Output2 { fn part2(input: &str) -> Self::Output2 {
// Calculate how many wins we have per game // Start out with one copy of every card
let wins: Vec<_> = input let mut copies = vec![1; input.lines().count()];
.lines()
.map(|line| { input.lines().enumerate().for_each(|(i, line)| {
// Get rid of the first part // Get rid of the first part
let (_, line) = line let (_, line) = line
.split_once(": ") .split_once(": ")
@ -109,26 +109,20 @@ impl aoc::Solver for Day {
let winning: Vec<_> = winning.split(' ').flat_map(str::parse::<usize>).collect(); let winning: Vec<_> = winning.split(' ').flat_map(str::parse::<usize>).collect();
// Parse the numbers we have, check if they are a winning number and count the // Parse the numbers we have, check if they are a winning number and count the
// amount of winning numbers we have // amount of winning numbers we have
numbers let wins = numbers
.split(' ') .split(' ')
.flat_map(str::parse::<usize>) .flat_map(str::parse::<usize>)
.filter(|num| winning.contains(num)) .filter(|num| winning.contains(num))
.count() .count();
})
.collect();
// Start out with one copy of every card // Increment the amount that we have of the cards that we win by the number we have of
let mut copies = vec![1; wins.len()]; // the current card
for j in (i + 1)..(i + wins + 1) {
// Keep track of how many copies we get of every card
for (i, win) in wins.iter().enumerate() {
for j in (i + 1)..(i + win + 1) {
// Add the current amount of copies to the card we win
// e.g. we have 2 copies of the current card that has 3 wins, this means we add 2 // e.g. we have 2 copies of the current card that has 3 wins, this means we add 2
// to the next 3 cards // to the next 3 cards
copies[j] += copies[i] copies[j] += copies[i]
} }
} });
copies.iter().sum() copies.iter().sum()
} }