summaryrefslogtreecommitdiffstats
path: root/src/2020/4/mod.rs
blob: 4b51b294ce8078ed597243ac3fe831842905fcf7 (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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
use anyhow::Context as _;

const REQUIRED_KEYS: &[&str] =
    &["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"];

pub fn part1() -> anyhow::Result<()> {
    let batch = crate::util::read_file_str("data/4.txt")?;
    let mut valid = 0;
    for passport in parse(&batch)? {
        let mut cur_valid = true;
        for key in REQUIRED_KEYS {
            if !passport.contains_key(&key.to_string()) {
                cur_valid = false;
                break;
            }
        }
        if cur_valid {
            valid += 1;
        }
    }
    println!("{}", valid);
    Ok(())
}

pub fn part2() -> anyhow::Result<()> {
    let batch = crate::util::read_file_str("data/4.txt")?;
    let mut valid = 0;
    for passport in parse(&batch)? {
        let mut cur_valid = true;
        for key in REQUIRED_KEYS {
            match passport.get(&key.to_string()) {
                Some(val) => {
                    if !validate(key, val)? {
                        cur_valid = false;
                        break;
                    }
                }
                None => {
                    cur_valid = false;
                    break;
                }
            }
        }
        if cur_valid {
            valid += 1;
        }
    }
    println!("{}", valid);
    Ok(())
}

fn parse(
    batch: &str,
) -> anyhow::Result<Vec<std::collections::HashMap<String, String>>> {
    let mut res = vec![];
    let mut cur = std::collections::HashMap::new();
    for line in batch.lines() {
        if line.is_empty() {
            res.push(cur);
            cur = std::collections::HashMap::new();
            continue;
        }

        for field in line.split(' ') {
            let mut parts = field.split(':');
            let key = parts.next().with_context(|| {
                format!("failed to parse field '{}'", field)
            })?;
            let value = parts.next().with_context(|| {
                format!("failed to parse field '{}'", field)
            })?;
            cur.insert(key.to_string(), value.to_string());
        }
    }
    if !cur.is_empty() {
        res.push(cur);
    }
    Ok(res)
}

fn validate(key: &str, val: &str) -> anyhow::Result<bool> {
    match key {
        "byr" => match val.parse::<i32>() {
            Ok(year) => Ok(year >= 1920 && year <= 2002),
            Err(_) => Ok(false),
        },
        "iyr" => match val.parse::<i32>() {
            Ok(year) => Ok(year >= 2010 && year <= 2020),
            Err(_) => Ok(false),
        },
        "eyr" => match val.parse::<i32>() {
            Ok(year) => Ok(year >= 2020 && year <= 2030),
            Err(_) => Ok(false),
        },
        "hgt" => {
            if val.len() < 3 {
                Ok(false)
            } else if val.ends_with("in") {
                match val[0..val.len() - 2].parse::<i32>() {
                    Ok(inches) => Ok(inches >= 59 && inches <= 76),
                    Err(_) => Ok(false),
                }
            } else if val.ends_with("cm") {
                match val[0..val.len() - 2].parse::<i32>() {
                    Ok(inches) => Ok(inches >= 150 && inches <= 193),
                    Err(_) => Ok(false),
                }
            } else {
                Ok(false)
            }
        }
        "hcl" => Ok(val.len() == 7
            && val.starts_with('#')
            && val[1..]
                == val[1..]
                    .matches(|c: char| c.is_ascii_hexdigit())
                    .collect::<String>()),
        "ecl" => Ok(val == "amb"
            || val == "blu"
            || val == "brn"
            || val == "gry"
            || val == "grn"
            || val == "hzl"
            || val == "oth"),
        "pid" => Ok(val.len() == 9
            && val
                == val
                    .matches(|c: char| c.is_ascii_digit())
                    .collect::<String>()),
        _ => Err(anyhow::anyhow!("invalid key found: {}", key)),
    }
}