# 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:

[...]

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,
}

impl Entry {
pub fn is_valid(&self, policy: Policy) -> bool {
match policy {
Policy::Old => {
let (start, end) = self.numbers;

let frequency =

(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()?,
})
}

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',
},
Entry {
numbers: (1, 3),
key: 'b',
},
Entry {
numbers: (2, 9),
key: 'c',
},
];

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',
},
);

Ok(())
}
}


src/bin/day_2_1.rs

use {
anyhow::Result,
aoc_2020::day_2::{self as lib, Entry, Policy},
std::{
fs::File,
},
};

fn main() -> anyhow::Result<()> {

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,
},
};

fn main() -> anyhow::Result<()> {

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(())
}


cargo fmt and cargo clippy have been applied.

Instead of implementing FromStr on Entry on your own, you may use crates such as parse-display, reformation or recap.

Some of the derives on Policy and Entry seem unnecessary.

Kudos for including tests. It makes the code easier to review.

In tests, when running assertions, I tend to name one of the arguments expected_foo, so that the assertion is shorter. Also, this makes it clear which argument is expected and which is the actual result. In your code:

assert_eq!(
text.parse::<Entry>()?,
Entry {
numbers: (1, 3),
key: 'a',
},
);


I would change to:

let expected_entry = Entry {
numbers: (1, 3),
key: 'a',
$$$$

• The expected_* one is excellent - it makes the code significantly more readable. Speaking of unnecessary derives, can you name the particular derives that you deem unnecessary? I derived the Eq series for testing, for example. Commented Jan 17, 2021 at 5:52
• @L.F. Glad it was helpful. After a cursory glance, the only needed ones are for testing: Debug, Eq + PartialEq on Entry. Other than that, derives can be removed: you dont hash Entry, you rarely use Policy, and you dont clone Entry. By the way, I would be curious how you'd solve day 19. Commented Jan 17, 2021 at 10:02
• I would generally derive Clone` as long as it makes sense to clone the type. I'm curious to know if there are any downsides to this. As for day 19, I'm thinking of writing a build script or procedural macro to generate a pest script. A little bit cheating, but we'll see :) Commented Jan 17, 2021 at 10:11