summaryrefslogtreecommitdiff
path: root/2021/day06/src/main.rs
diff options
context:
space:
mode:
Diffstat (limited to '2021/day06/src/main.rs')
-rw-r--r--2021/day06/src/main.rs48
1 files changed, 48 insertions, 0 deletions
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 @@
1use std::fs;
2use std::path::Path;
3
4/* AOC21 Day 6: https://adventofcode.com/2021/day/6 */
5fn main() {
6 let input = Path::new("resources").join("input.txt");
7 let content = fs::read_to_string(input).expect("Unable to read input file");
8 println!("Ex1: The number of lanternfishes is {}", evolution(parse_input(&content), 80));
9 println!("Ex2: The number of lanternfishes is {}", evolution(parse_input(&content), 256));
10}
11
12fn parse_input(s: &str) -> Vec<u64> {
13 let mut lfs = vec![0;9];
14 s.split(",").for_each(|n| lfs[n.parse::<usize>().expect("Malformed input")] += 1);
15 lfs
16}
17
18fn evolution(mut lfs: Vec<u64>, days: usize) -> u64 {
19 (1..days).for_each(|i| lfs[(i+7)%9] += lfs[i%9]);
20 lfs.iter().sum()
21}
22
23#[cfg(test)]
24mod tests {
25 use super::*;
26
27 const LANTERNFISHES: &str = "3,4,3,1,2";
28
29 #[test]
30 fn input_parsing() {
31 assert_eq!(vec![0,1,1,2,1,0,0,0,0], parse_input("3,4,3,1,2"))
32 }
33
34 #[test]
35 fn evolution_18days() {
36 assert_eq!(26, evolution(parse_input(LANTERNFISHES), 18))
37 }
38
39 #[test]
40 fn evolution_80days() {
41 assert_eq!(5934, evolution(parse_input(LANTERNFISHES), 80))
42 }
43
44 #[test]
45 fn evolution_256days() {
46 assert_eq!(26984457539, evolution(parse_input(LANTERNFISHES), 256))
47 }
48}