advent_of_code/year2023/
day04.rs1use crate::input::{on_error, Input};
2
3pub fn solve(input: &Input) -> Result<u64, String> {
4 const MAX_WINNING_NUMBERS: usize = 16;
5 let multiplier_stack = &mut [1; MAX_WINNING_NUMBERS];
6 let mut multiplier_idx = 0;
7
8 input
9 .text
10 .lines()
11 .map(|card_str| {
12 let card_str = card_str.split_once(": ").ok_or_else(on_error)?.1;
13 let (win_numbers, my_numbers) = card_str.split_once(" | ").ok_or_else(on_error)?;
14
15 let mut winning_bitmask = 0_u128;
16 for number in win_numbers.split_ascii_whitespace() {
17 let number = parse_number(number)?;
18 winning_bitmask |= 1 << number;
19 }
20
21 let mut points = 0;
22 for number in my_numbers.split_ascii_whitespace() {
23 let number = parse_number(number)?;
24 if winning_bitmask & (1 << number) != 0 {
25 points = if input.is_part_one() && points != 0 {
26 points * 2
27 } else {
28 points + 1
29 };
30 }
31 }
32
33 Ok(if input.is_part_one() {
34 points as u64
35 } else {
36 let num_copies = multiplier_stack[multiplier_idx];
37 multiplier_stack[multiplier_idx] = 1;
38 for i in 1..=points {
39 multiplier_stack[(multiplier_idx + i) % MAX_WINNING_NUMBERS] += num_copies;
40 }
41 multiplier_idx = (multiplier_idx + 1) % MAX_WINNING_NUMBERS;
42 num_copies
43 })
44 })
45 .sum()
46}
47
48fn parse_number(num_str: &str) -> Result<u8, String> {
49 let n = num_str.parse::<u8>().map_err(|_| on_error())?;
50 if n >= 128 {
51 return Err(on_error());
52 }
53 Ok(n)
54}
55
56#[test]
57pub fn tests() {
58 use crate::input::{test_part_one_no_allocations, test_part_two_no_allocations};
59
60 let test_input = "Card 1: 41 48 83 86 17 | 83 86 6 31 17 9 48 53
61Card 2: 13 32 20 16 61 | 61 30 68 82 17 32 24 19
62Card 3: 1 21 53 59 44 | 69 82 63 72 16 21 14 1
63Card 4: 41 92 73 84 69 | 59 84 76 51 58 5 54 83
64Card 5: 87 83 26 28 32 | 88 30 70 12 93 22 82 36
65Card 6: 31 18 13 56 72 | 74 77 10 23 35 67 36 11";
66 test_part_one_no_allocations!(test_input => 13);
67 test_part_two_no_allocations!(test_input => 30);
68
69 let real_input = include_str!("day04_input.txt");
70 test_part_one_no_allocations!(real_input => 17803);
71 test_part_two_no_allocations!(real_input => 5_554_894);
72 let real_input = include_str!("day04_input_other.txt");
73 test_part_two_no_allocations!(real_input => 6_420_979);
74}