aoc/year2021/
day06.rs

1//! # Lanternfish
2//!
3//! The key observation is that all fish of the same age behave the same, so we only
4//! need to store the *total* of each fish per day, rather than each fish individually.
5//!
6//! Another optimization trick is rather than modifying the array by removing the fish at day 0,
7//! then shifting each fish total down by 1, we can simply increment what we consider the
8//! head of the array modulo 9 to achieve the same effect in place.
9use crate::util::parse::*;
10
11type Input = [u64; 9];
12
13pub fn parse(input: &str) -> Input {
14    let mut fish = [0_u64; 9];
15    input.iter_unsigned().for_each(|i: usize| fish[i] += 1);
16    fish
17}
18
19pub fn part1(input: &Input) -> u64 {
20    simulate(input, 80)
21}
22
23pub fn part2(input: &Input) -> u64 {
24    simulate(input, 256)
25}
26
27fn simulate(input: &Input, days: usize) -> u64 {
28    let mut fish = *input;
29    (0..days).for_each(|day| fish[(day + 7) % 9] += fish[day % 9]);
30    fish.iter().sum()
31}