summaryrefslogtreecommitdiff
path: root/2021/day06/src/main.rs
blob: e3ef79c2a2e29005f9e00e59904f25338fdc4b3d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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<u64> {
    let mut lfs = vec![0;9];
    s.split(",").for_each(|n| lfs[n.parse::<usize>().expect("Malformed input")] += 1);
    lfs
}

fn evolution(mut lfs: Vec<u64>, 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))
    }
}