From 64e22194d39d2914db1e3bf93c90de9e0791d9b3 Mon Sep 17 00:00:00 2001 From: Federico Igne Date: Fri, 1 Dec 2023 09:21:16 +0100 Subject: chore: reorganize project structure --- 2021/day06/src/main.rs | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 2021/day06/src/main.rs (limited to '2021/day06/src/main.rs') diff --git a/2021/day06/src/main.rs b/2021/day06/src/main.rs new file mode 100644 index 0000000..e3ef79c --- /dev/null +++ b/2021/day06/src/main.rs @@ -0,0 +1,48 @@ +use std::fs; +use std::path::Path; + +/* AOC21 Day 6: https://adventofcode.com/2021/day/6 */ +fn main() { + let input = Path::new("resources").join("input.txt"); + let content = fs::read_to_string(input).expect("Unable to read input file"); + println!("Ex1: The number of lanternfishes is {}", evolution(parse_input(&content), 80)); + println!("Ex2: The number of lanternfishes is {}", evolution(parse_input(&content), 256)); +} + +fn parse_input(s: &str) -> Vec { + let mut lfs = vec![0;9]; + s.split(",").for_each(|n| lfs[n.parse::().expect("Malformed input")] += 1); + lfs +} + +fn evolution(mut lfs: Vec, days: usize) -> u64 { + (1..days).for_each(|i| lfs[(i+7)%9] += lfs[i%9]); + lfs.iter().sum() +} + +#[cfg(test)] +mod tests { + use super::*; + + const LANTERNFISHES: &str = "3,4,3,1,2"; + + #[test] + fn input_parsing() { + assert_eq!(vec![0,1,1,2,1,0,0,0,0], parse_input("3,4,3,1,2")) + } + + #[test] + fn evolution_18days() { + assert_eq!(26, evolution(parse_input(LANTERNFISHES), 18)) + } + + #[test] + fn evolution_80days() { + assert_eq!(5934, evolution(parse_input(LANTERNFISHES), 80)) + } + + #[test] + fn evolution_256days() { + assert_eq!(26984457539, evolution(parse_input(LANTERNFISHES), 256)) + } +} -- cgit v1.2.3