summaryrefslogtreecommitdiff
path: root/2021/rust/day01/src/main.rs
blob: d0ac9325a8c41a4590a8def1aa1f1ec6712e7d89 (plain)
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
use {
    anyhow::{
        anyhow,
        Context,
        Result,
    },
    std::{
        env::args,
        fs::File,
        io::{
            BufRead,
            BufReader,
        },
        path::Path,
    },
};

fn read_input<T: AsRef<Path>>(filename: T) -> Result<Vec<usize>> {
    let reader = BufReader::new(File::open(filename)?);

    reader.lines().map(
        |v| v?.parse().map_err(|err| anyhow!("Could not parse input: {}", err))
    ).collect()
}

#[derive(PartialEq)]
enum Change {
    NoPrevVal,
    Increased,
    Decreased,
    Identical,
}

fn count_increases<'a, I: IntoIterator<Item = &'a usize>>(values: I) -> usize {
    values.into_iter().scan(None, |state, val| {
        let next = match state {
            None => Change::NoPrevVal,
            Some(prev) if val < *prev => Change::Decreased,
            Some(prev) if val > *prev => Change::Increased,
            Some(prev) if val == *prev => Change::Identical,
            Some(_) => unreachable!(),
        };
        *state = Some(val);
        Some(next)
    }).filter(|change| change == &Change::Increased).count()
}

fn part1<'a, I: IntoIterator<Item = &'a usize>>(input: I) -> Result<usize> {
    let count = count_increases(input);

    Ok(count)
}

fn part2<'a, I: IntoIterator<Item = &'a usize> + Copy>(input: I) -> Result<usize> {
    let left_iter = input.into_iter();
    let middle_iter = input.into_iter().skip(1);
    let right_iter = input.into_iter().skip(2);
    let slidesums: Vec<_> = left_iter.zip(middle_iter).zip(right_iter).map(|n| {
        let ((first, second), third) = n;
        first + second + third
    }).collect();
    let count = count_increases(&slidesums);

    Ok(count)
}

fn main() -> Result<()> {
    let ( do_part_1, do_part_2 ) = aoc::do_parts();

    let filename = args().nth(1).ok_or(anyhow!("Missing input filename"))?;
    let input = read_input(filename).context("Could not read input")?;
    if do_part_1 {
        let solution = part1(&input).context("No solution for part 1")?;
        println!("Part1, number of increases found to be: {}", solution);
    }
    if do_part_2 {
        let solution = part2(&input).context("No solution for part 2")?;
        println!("Part2, number of increases found to be: {}", solution);
    }
    Ok(())
}