advent_of_code/year2020/
day02.rs1use crate::input::Input;
2
3pub fn solve(input: &Input) -> Result<u32, String> {
4 let mut valid_passwords = 0;
5
6 for (line_index, line) in input.text.lines().enumerate() {
7 let on_error = || {
8 format!(
9 "Line {}: Invalid format - expected '$START-$END $CHAR: $PASSWORD'",
10 line_index + 1
11 )
12 };
13
14 let (password_policy_str, password) = line.split_once(": ").ok_or_else(on_error)?;
15
16 let mut policy_parts = password_policy_str.split(' ');
17 let mut occurrences_parts = policy_parts.next().ok_or_else(on_error)?.split('-');
18 let policy_char = policy_parts
19 .next()
20 .ok_or_else(on_error)?
21 .chars()
22 .next()
23 .ok_or_else(on_error)?;
24
25 let policy_start = occurrences_parts
26 .next()
27 .ok_or_else(on_error)?
28 .parse::<usize>()
29 .map_err(|_| on_error())?;
30 let policy_end = occurrences_parts
31 .next()
32 .ok_or_else(on_error)?
33 .parse::<usize>()
34 .map_err(|_| on_error())?;
35
36 if input.is_part_one() {
37 let actual_occurrences = password.chars().filter(|&c| c == policy_char).count();
38 if (policy_start..=policy_end).contains(&actual_occurrences) {
39 valid_passwords += 1;
40 }
41 } else {
42 let correct_count = password
43 .chars()
44 .enumerate()
45 .filter(|(index, c)| {
46 (policy_start == index + 1 || policy_end == index + 1) && *c == policy_char
47 })
48 .count();
49 if correct_count == 1 {
50 valid_passwords += 1;
51 }
52 }
53 }
54 Ok(valid_passwords)
55}
56
57#[test]
58pub fn tests() {
59 test_part_one!("1-3 a: abcde\n1-3 b: cdefg\n2-9 c: ccccccccc" => 2);
60 test_part_two!("1-3 a: abcde\n1-3 b: cdefg\n2-9 c: ccccccccc" => 1);
61
62 test_part_one_error!("1- b: asdf" => "Line 1: Invalid format - expected '$START-$END $CHAR: $PASSWORD'");
63 test_part_two_error!("1-3 a: asdf\nhi\n" => "Line 2: Invalid format - expected '$START-$END $CHAR: $PASSWORD'");
64
65 let real_input = include_str!("day02_input.txt");
66 test_part_one!(real_input => 636);
67 test_part_two!(real_input => 588);
68}