AoC2021/src/day06.rs

66 lines
1.5 KiB
Rust

use crate::Day;
use anyhow::Result;
pub struct Day06([u64; 9]);
impl Day for Day06 {
fn init(content: String) -> anyhow::Result<Self> {
let c = content.split(',').map(str::parse).collect::<Result<Vec<usize>, _>>()?;
let mut w: [u64; 9] = [0, 0, 0, 0, 0, 0, 0, 0, 0];
for z in c {
w[z as usize] += 1;
}
Ok(Self(w))
}
fn part1(&self) -> Result<String> {
Ok(format!("{}", self.do_magic(80)))
}
fn part2(&self) -> Result<String> {
Ok(format!("{}", self.do_magic(256)))
}
}
impl Day06 {
fn do_magic(&self, days: u64) -> u64 {
(0..days).fold(self.0, Self::foo).iter().sum()
}
#[allow(clippy::many_single_char_names)]
fn foo([a, b, c, d, e, f, g, h, i]: [u64; 9], _: u64) -> [u64; 9] {
[b, c, d, e, f, g, h + a, i, a]
}
}
#[cfg(test)]
mod tests {
use crate::day06::Day06;
use crate::day::Day;
use anyhow::Result;
use crate::day_tests;
const INPUT: &str = r"3,4,3,1,2";
#[test]
fn part1_test() -> Result<()> {
let d = Day06::init(INPUT.to_string())?;
assert_eq!("5934", d.part1()?);
Ok(())
}
#[test]
fn part2_test() -> Result<()> {
let d = Day06::init(INPUT.to_string())?;
assert_eq!("26984457539", d.part2()?);
Ok(())
}
day_tests!(Day06, "06", "362740", "1644874076764");
#[test]
fn youri_test() -> Result<()> {
let d = Day06::init(String::from("3,4,3,1,2"))?;
assert_eq!(17614907331943978900, d.do_magic(489));
Ok(())
}
}