0
\$\begingroup\$

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

Next: Advent of Code 2020 - Day 3: tobogganing down a slope

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.

\$\endgroup\$
1
\$\begingroup\$

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',
        password: "abcde".to_owned(),
    },
);

I would change to:

let expected_entry = Entry {
    numbers: (1, 3),
    key: 'a',
    password: "abcde".to_owned(),
};

assert_eq!(text.parse::<Entry>()?, expected_entry);
```
\$\endgroup\$
5
  • \$\begingroup\$ 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. \$\endgroup\$
    – L. F.
    Jan 17 at 5:52
  • \$\begingroup\$ @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. \$\endgroup\$ Jan 17 at 10:02
  • \$\begingroup\$ 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 :) \$\endgroup\$
    – L. F.
    Jan 17 at 10:11
  • 1
    \$\begingroup\$ @L.F. I believe there are no downsides to deriving anything, except that a type may no longer support the derive in future versions. So backwards compatibility is the only concern. For clone, the situation is good as you rarely need to remove it. Obviously your program is a binary, not a library, so you have an easier job here. \$\endgroup\$ Jan 17 at 10:24
  • \$\begingroup\$ @L.F. Ah, it is the case that with many types and many dervives, the compilation takes longer. It used to be the case that for some derives, their compilation took O(n**2), but it was fixed. \$\endgroup\$ Jan 17 at 10:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.