Skip to main content
replace inappopriate tag
Link
L. F.
  • 9.7k
  • 2
  • 27
  • 70
Source Link
L. F.
  • 9.7k
  • 2
  • 27
  • 70

Advent of Code 2020 - Day 2: validating passwords

Previous: Advent of Code 2020 - Day 1: finding 2 or 3 numbers that add up to 2020

Problem statement

I decided to take a shot at Advent of Code 2020 to exercise my Rust knowledge. Here's the task for Day 2:

Day 2: Password Philosophy

[...]

To try to debug the problem, they have created a list (your puzzle input) of passwords (according to the corrupted database) and the corporate policy when that password was set.

For example, suppose you have the following list:

1-3 a: abcde 1-3 b: cdefg 2-9 c: ccccccccc 

Each line gives the password policy and then the password. The password policy indicates the lowest and highest number of times a given letter must appear for the password to be valid. For example, 1-3 a means that the password must contain a at least 1 time and at most 3 times.

In the above example, 2 passwords are valid. The middle password, cdefg, is not; it contains no instances of b, but needs at least 1. The first and third passwords are valid: they contain one a or nine c, both within the limits of their respective policies.

How many passwords are valid according to their policies?

[...]

Part Two

While it appears you validated the passwords correctly, they don't seem to be what the Official Toboggan Corporate Authentication System is expecting.

The shopkeeper suddenly realizes that he just accidentally explained the password policy rules from his old job at the sled rental place down the street! The Official Toboggan Corporate Policy actually works a little differently.

Each policy actually describes two positions in the password, where 1 means the first character, 2 means the second character, and so on. (Be careful; Toboggan Corporate Policies have no concept of "index zero"!) Exactly one of these positions must contain the given letter. Other occurrences of the letter are irrelevant for the purposes of policy enforcement.

Given the same example list from above:

  • 1-3 a: abcde is valid: position 1 contains a and position 3 does not.
  • 1-3 b: cdefg is invalid: neither position 1 nor position 3 contains b.
  • 2-9 c: ccccccccc is invalid: both position 2 and position 9 contain c.

How many passwords are valid according to the new interpretation of the policies?

The full story can be found on the website.

My solution

src/day_2.rs

use { anyhow::{anyhow, Result}, itertools::{self, Itertools}, std::str::FromStr, }; pub const PATH: &str = "./data/day_2/input"; #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum Policy { Old, New, } #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub struct Entry { pub numbers: (usize, usize), pub key: char, pub password: String, } impl Entry { pub fn is_valid(&self, policy: Policy) -> bool { match policy { Policy::Old => { let (start, end) = self.numbers; let frequency = self.password.chars().filter(|&c| c == self.key).count(); (start..=end).contains(&frequency) } Policy::New => { let (num_a, num_b) = self.numbers; let pos_a = num_a - 1; let pos_b = num_b - 1; let char_a = match self.password.chars().nth(pos_a) { Some(c) => c, None => return false, }; let char_b = match self.password.chars().nth(pos_b) { Some(c) => c, None => return false, }; (char_a == self.key) ^ (char_b == self.key) } } } } impl FromStr for Entry { type Err = anyhow::Error; fn from_str(text: &str) -> Result<Self> { fn parse(text: &str) -> Option<Entry> { let (policy, password) = text.split(": ").collect_tuple()?; let (range, key) = policy.split(" ").collect_tuple()?; let numbers = itertools::process_results( range.split("-").map(str::parse), |iter| iter.collect_tuple(), ) .ok()??; Some(Entry { numbers, key: key.parse().ok()?, password: String::from(password), }) } parse(text).ok_or_else(|| anyhow!("invalid entry")) } } #[cfg(test)] mod tests { use super::*; #[test] fn entry_is_valid() { let entries = [ Entry { numbers: (1, 3), key: 'a', password: "abcde".to_owned(), }, Entry { numbers: (1, 3), key: 'b', password: "cdefg".to_owned(), }, Entry { numbers: (2, 9), key: 'c', password: "ccccccccc".to_owned(), }, ]; assert!(entries[0].is_valid(Policy::Old)); assert!(!entries[1].is_valid(Policy::Old)); assert!(entries[2].is_valid(Policy::Old)); assert!(entries[0].is_valid(Policy::New)); assert!(!entries[1].is_valid(Policy::New)); assert!(!entries[2].is_valid(Policy::New)); } #[test] fn entry_from_str() -> Result<()> { let text = "1-3 a: abcde"; assert_eq!( text.parse::<Entry>()?, Entry { numbers: (1, 3), key: 'a', password: "abcde".to_owned(), }, ); Ok(()) } } 

src/bin/day_2_1.rs

use { anyhow::Result, aoc_2020::day_2::{self as lib, Entry, Policy}, std::{ fs::File, io::{prelude::*, BufReader}, }, }; fn main() -> anyhow::Result<()> { let file = BufReader::new(File::open(lib::PATH)?); let valid_count = itertools::process_results( file.lines() .map(|line| -> Result<_> { Ok(line?.parse::<Entry>()?) }), |entries| entries.filter(|entry| entry.is_valid(Policy::Old)).count(), )?; println!("{}", valid_count); Ok(()) } 

src/bin/day_2_2.rs

use { anyhow::Result, aoc_2020::day_2::{self as lib, Entry, Policy}, std::{ fs::File, io::{prelude::*, BufReader}, }, }; fn main() -> anyhow::Result<()> { let file = BufReader::new(File::open(lib::PATH)?); let valid_count = itertools::process_results( file.lines() .map(|line| -> Result<_> { Ok(line?.parse::<Entry>()?) }), |entries| entries.filter(|entry| entry.is_valid(Policy::New)).count(), )?; println!("{}", valid_count); Ok(()) } 

Crates used: anyhow 1.0.37 itertools 0.10.0

cargo fmt and cargo clippy have been applied.