Skip to main content

advent_of_code/year2021/
day06.rs

1use crate::input::Input;
2
3pub fn solve(input: &Input) -> Result<u64, String> {
4    const MAX_DAYS: usize = 9;
5
6    // Indexed by days left mapping to number of fishes with that many days left:
7    let mut count_per_day_left = [0; MAX_DAYS];
8
9    for day_left_str in input.text.split(',') {
10        match day_left_str.parse::<u8>() {
11            Ok(day_left) if day_left <= 8 => {
12                count_per_day_left[day_left as usize] += 1;
13            }
14            _ => {
15                return Err(
16                    "Input is not comma-separated list of integers in the range [0,8].".to_string(),
17                );
18            }
19        }
20    }
21
22    for day in 0..input.part_values(80, 256) {
23        // Those with 0 days left have given birth to new ones with 8 days
24        // left - but we need to also add them back (reset to 6 days left):
25        count_per_day_left[(7 + day) % MAX_DAYS] += count_per_day_left[day % MAX_DAYS];
26    }
27
28    Ok(count_per_day_left.iter().sum())
29}
30
31#[test]
32pub fn tests() {
33    let example = "3,4,3,1,2";
34    test_part_one!(example => 5934);
35    test_part_two!(example => 26_984_457_539);
36
37    let real_input = include_str!("day06_input.txt");
38    test_part_one!(real_input => 387_413);
39    test_part_two!(real_input => 1_738_377_086_345);
40}