summaryrefslogtreecommitdiffstats
path: root/src/2020/2/mod.rs
blob: a2ff9df31c6ae63b9f2732780e3772581edd7bf0 (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
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
use crate::prelude::*;

pub struct Line {
    c: char,
    n1: usize,
    n2: usize,
    password: String,
}

impl Line {
    fn parse(line: &str) -> Result<Self> {
        let captures =
            regex_captures!(r"^([0-9]+)-([0-9]+) (.): (.*)$", line)
                .context("line failed to match regex")?;
        let c = captures
            .get(3)
            .unwrap()
            .as_str()
            .parse()
            .context("invalid policy char")?;
        let n1 = captures
            .get(1)
            .unwrap()
            .as_str()
            .parse()
            .context("invalid policy lower bound")?;
        let n2 = captures
            .get(2)
            .unwrap()
            .as_str()
            .parse()
            .context("invalid policy upper bound")?;
        let password = captures.get(4).unwrap().as_str().to_string();
        Ok(Self {
            c,
            n1,
            n2,
            password,
        })
    }

    fn valid_part_1(&self) -> bool {
        let count = self.password.chars().filter(|c| *c == self.c).count();
        count >= self.n1 && count <= self.n2
    }

    fn valid_part_2(&self) -> bool {
        (self.password.chars().nth(self.n1 - 1) == Some(self.c))
            ^ (self.password.chars().nth(self.n2 - 1) == Some(self.c))
    }
}

pub fn parse(fh: File) -> Result<impl Iterator<Item = Line>> {
    Ok(parse::lines(fh).map(|line| Line::parse(&line).unwrap()))
}

pub fn part1(lines: impl Iterator<Item = Line>) -> Result<i64> {
    let count = lines.filter(|l| l.valid_part_1()).count();
    Ok(count.try_into()?)
}

pub fn part2(lines: impl Iterator<Item = Line>) -> Result<i64> {
    let count = lines.filter(|l| l.valid_part_2()).count();
    Ok(count.try_into()?)
}

#[test]
fn test() {
    assert_eq!(
        part1(parse(parse::data(2020, 2).unwrap()).unwrap()).unwrap(),
        638
    );
    assert_eq!(
        part2(parse(parse::data(2020, 2).unwrap()).unwrap()).unwrap(),
        699
    );
}