From c8734354d4d7cc4fb822f426ef9f32a787420bb4 Mon Sep 17 00:00:00 2001 From: Federico Igne Date: Mon, 6 Dec 2021 14:33:31 +0000 Subject: Day 6 --- day6/Cargo.toml | 9 +++++++++ day6/resources/input.txt | 1 + day6/src/main.rs | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 58 insertions(+) create mode 100644 day6/Cargo.toml create mode 100644 day6/resources/input.txt create mode 100644 day6/src/main.rs (limited to 'day6') diff --git a/day6/Cargo.toml b/day6/Cargo.toml new file mode 100644 index 0000000..422ffef --- /dev/null +++ b/day6/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "day6" +version = "0.1.0" +authors = ["Federico Igne "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/day6/resources/input.txt b/day6/resources/input.txt new file mode 100644 index 0000000..c35cc57 --- /dev/null +++ b/day6/resources/input.txt @@ -0,0 +1 @@ +5,1,1,5,4,2,1,2,1,2,2,1,1,1,4,2,2,4,1,1,1,1,1,4,1,1,1,1,1,5,3,1,4,1,1,1,1,1,4,1,5,1,1,1,4,1,2,2,3,1,5,1,1,5,1,1,5,4,1,1,1,4,3,1,1,1,3,1,5,5,1,1,1,1,5,3,2,1,2,3,1,5,1,1,4,1,1,2,1,5,1,1,1,1,5,4,5,1,3,1,3,3,5,5,1,3,1,5,3,1,1,4,2,3,3,1,2,4,1,1,1,1,1,1,1,2,1,1,4,1,3,2,5,2,1,1,1,4,2,1,1,1,4,2,4,1,1,1,1,4,1,3,5,5,1,2,1,3,1,1,4,1,1,1,1,2,1,1,4,2,3,1,1,1,1,1,1,1,4,5,1,1,3,1,1,2,1,1,1,5,1,1,1,1,1,3,2,1,2,4,5,1,5,4,1,1,3,1,1,5,5,1,3,1,1,1,1,4,4,2,1,2,1,1,5,1,1,4,5,1,1,1,1,1,1,1,1,1,1,3,1,1,1,1,1,4,2,1,1,1,2,5,1,4,1,1,1,4,1,1,5,4,4,3,1,1,4,5,1,1,3,5,3,1,2,5,3,4,1,3,5,4,1,3,1,5,1,4,1,1,4,2,1,1,1,3,2,1,1,4 \ No newline at end of file diff --git a/day6/src/main.rs b/day6/src/main.rs new file mode 100644 index 0000000..e3ef79c --- /dev/null +++ b/day6/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