From f61ff1b317fd5308cb370558facb76b6e7544ad6 Mon Sep 17 00:00:00 2001 From: Reiner Herrmann Date: Mon, 4 Dec 2023 11:45:57 +0100 Subject: day4 solution 2 --- src/bin/day4.rs | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/src/bin/day4.rs b/src/bin/day4.rs index ffd5d0b..94e3853 100644 --- a/src/bin/day4.rs +++ b/src/bin/day4.rs @@ -5,7 +5,7 @@ static DAY: u8 = 4; fn main() { let input = advent::read_lines(DAY); println!("{DAY}a: {}", total_points(&input)); - println!("{DAY}b: {}", 0); + println!("{DAY}b: {}", total_cards(&input)); } struct Card { @@ -44,6 +44,23 @@ fn total_points(input: &[String]) -> u32 { .sum() } +fn total_cards(input: &[String]) -> u32 { + let cards = input.iter() + .map(|x| Card::new(x)) + .collect::>(); + let mut amounts = vec![1; cards.len()]; + + for (i, card) in cards.iter().enumerate() { + let matches = card.matching_numbers().len(); + let copies = amounts[i]; + for amount in amounts.iter_mut().take(i + 1 + matches).skip(i + 1) { + *amount += copies; + } + } + + amounts.iter().sum() +} + #[cfg(test)] mod tests { use super::*; @@ -59,5 +76,6 @@ mod tests { "Card 6: 31 18 13 56 72 | 74 77 10 23 35 67 36 11", ].iter().map(|&x| String::from(x)).collect::>(); assert_eq!(total_points(&input), 13); + assert_eq!(total_cards(&input), 30); } } -- cgit v1.2.3