~xenrox/aoc2020

e1b0047d2e8e148d021eb4678e20dcac11533baf — Thorben Günther 1 year, 5 months ago 768c9d2
Solve day 2 part 2
1 files changed, 27 insertions(+), 4 deletions(-)

M src/days/day02.rs
M src/days/day02.rs => src/days/day02.rs +27 -4
@@ 28,7 28,7 @@ fn parse_contents(contents: String) -> Vec<Policy> {
    policies
}

fn count_valid_passwords(policies: &Vec<Policy>) -> i32 {
fn count_valid_passwords1(policies: &Vec<Policy>) -> i32 {
    let mut count_valid = 0;
    for policy in policies {
        let count = policy.password.matches(policy.letter).count();


@@ 39,12 39,25 @@ fn count_valid_passwords(policies: &Vec<Policy>) -> i32 {
    count_valid
}

fn count_valid_passwords2(policies: &Vec<Policy>) -> i32 {
    let mut count_valid = 0;
    for policy in policies {
        let first = policy.password.chars().nth(policy.min - 1).unwrap();
        let second = policy.password.chars().nth(policy.max - 1).unwrap();
        if (first == policy.letter) ^ (second == policy.letter) {
            count_valid += 1;
        }
    }
    count_valid
}

pub fn get_solution() {
    let contents = fs::read_to_string("data/day02.dat").expect("Could not read data");
    let policies = parse_contents(contents);
    let count_valid = count_valid_passwords(&policies);
    let count_valid1 = count_valid_passwords1(&policies);
    let count_valid2 = count_valid_passwords2(&policies);

    println!("Day 2, part 1: {}", count_valid);
    println!("Day 2, part 1: {}, part 2: {}", count_valid1, count_valid2);
}

#[cfg(test)]


@@ 58,6 71,16 @@ mod tests {
            1-3 b: cdefg
            2-9 c: ccccccccc",
        );
        assert_eq!(count_valid_passwords(&parse_contents(contents)), 2);
        assert_eq!(count_valid_passwords1(&parse_contents(contents)), 2);
    }

    #[test]
    fn part2() {
        let contents = String::from(
            "1-3 a: abcde
            1-3 b: cdefg
            2-9 c: ccccccccc",
        );
        assert_eq!(count_valid_passwords2(&parse_contents(contents)), 1);
    }
}