1
\$\begingroup\$

Original: Advent of Code 2020 - Day 2: validating passwords

Problem statement

I decided to translate my Rust solution to Advent of Code 2020 into C++ to increase my familiarity with C++. 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

lib.hpp

#ifndef INC_LIB_HPP_KwANAGBG9S
#define INC_LIB_HPP_KwANAGBG9S

#include <algorithm>
#include <cstddef>
#include <iostream>
#include <string>
#include <utility>

// must be NTBS
constexpr const char* PATH = "./data/day_2/input";

enum class Policy { Old, New };

struct Entry {
    std::pair<std::size_t, std::size_t> numbers;
    std::string password;
    char key;

    bool is_valid(Policy policy) const {
        switch (policy) {
        case Policy::Old: {
            auto frequency = static_cast<std::size_t>(
                std::count(password.begin(), password.end(), key)
            );
            return frequency >= numbers.first && frequency <= numbers.second;
        }
        case Policy::New: {
            auto pos_a = numbers.first - 1;
            auto pos_b = numbers.second - 1;

            if (pos_a >= password.size() || pos_b >= password.size()) {
                return false;
            }

            // logical xor
            return (password[pos_a] == key) != (password[pos_b] == key);
        }
        }
    }
};

// error checking omitted
inline std::istream& operator>>(std::istream& is, Entry& entry) {
    is >> entry.numbers.first;
    is.get(); // consume '-'
    is >> entry.numbers.second >> entry.key;
    is.get(); // consume ':'
    is >> entry.password;

    return is;
}

#endif

main.cpp

#include "lib.hpp"
#include <fstream>

int main() {
    std::ifstream file{PATH};

    std::size_t valid_count_old = 0;
    std::size_t valid_count_new = 0;

    for (Entry entry; file >> entry;) {
        if (entry.is_valid(Policy::Old)) {
            ++valid_count_old;
        }
        if (entry.is_valid(Policy::New)) {
            ++valid_count_new;
        }
    }

    std::cout << "Part One: " << valid_count_old << '\n'
              << "Part Two: " << valid_count_new << '\n';
}
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

unnecessary global:

constexpr const char* PATH = "./data/day_2/input";

Not sure this should be a global in the header file. It could just be a local variable in main().


naming:

Note that "policy" in the instructions refers to the special character and accompanying numbers.

The Policy enum in the code, might more accurately be called AuthSystem or PolicyType.


design:

The Entry class is fine for data input, but I don't think password validation should be built into it (the member variables actually represent different things depending on the authentication system we use, even if we happen to use the same struct for data input at the moment).

Since we need an if statement to separate the two password policies in main(). Having a Policy enum and a switch statement inside the password checking function is not necessary.

We can have two free functions, one for each authentication system, and simple (unrelated) structs with correct variable names for the policy data:

struct OldPolicy{ char key_char; std::size_t min_key_freq; std::size_t max_key_freq; };
bool is_password_valid(std::string const& password, OldPolicy policy);

struct NewPolicy { char key_char; std::size_t first_key_index; std::size_t second_key_index; };
bool is_password_valid(std::string const& password, NewPolicy policy);

check policies on input:

We should have a separate step validating the policy before we try to use the policy to check the password:

  • Check that min and max frequencies are a valid range (not zero, min is less than max).
  • Check that the indices are valid (not the same, not zero).
  • Convert to zero-based indices (so the subtraction happens in one place only).

If something goes wrong here we should throw, instead of trying to check the password.


I think I'd go with something a bit like this:

#include <signal.h>

void die() { raise(SIGTRAP); } // __debugbreak(); // msvc
void die_if(bool condition) { if (condition) die(); }

#include <algorithm>
#include <cstddef>
#include <exception>
#include <string>

namespace old_auth
{

    struct Policy
    {
        char key;
        std::size_t min_key_freq, max_key_freq;
    };

    bool is_password_valid(std::string const& password, Policy policy)
    {
        die_if(policy.min_key_freq > policy.max_key_freq);

        if (password.size() < policy.min_key_freq) return false;

        auto key_count = static_cast<std::size_t>(std::count(password.begin(), password.end(), policy.key));
        return (key_count >= policy.min_key_freq && key_count <= policy.max_key_freq);
    }
    
} // old_auth

namespace new_auth
{

    struct Policy
    {   
        char key;
        std::size_t key_index_1, key_index_2;
    };

    bool is_password_valid(std::string const& password, Policy policy)
    {
        die_if(policy.key_index_1 == policy.key_index_2);

        if (policy.key_index_1 >= password.size()) return false;
        if (policy.key_index_2 >= password.size()) return false;

        return (password[policy.key_index_1] == policy.key) != (password[policy.key_index_2] == policy.key);
    }
    
} // new_auth

#include <cstddef>
#include <fstream>
#include <iostream>

struct Entry
{
    char key;
    std::size_t a, b;
    std::string password;
};

std::istream& operator>>(std::istream& is, Entry& entry)
{
    is >> entry.a;
    is.get();
    is >> entry.b;
    is >> entry.key;
    is.get();
    is >> entry.password;
    
    return is;
}

// maybe this should be a constructor?
old_auth::Policy make_old_auth_policy(char key, std::size_t min_key_freq, std::size_t max_key_freq)
{
    if (min_key_freq > max_key_freq || min_key_freq == 0)
        throw std::runtime_error("invalid password policy (old)");

    return { key, min_key_freq, max_key_freq };
}

// maybe this should be a constructor? but I don't like doing the index conversion there...
new_auth::Policy make_new_auth_policy(char key, std::size_t one_based_key_pos_1, std::size_t one_based_key_pos_2)
{
    if (one_based_key_pos_1 == 0 || one_based_key_pos_2 == 0 || one_based_key_pos_1 == one_based_key_pos_2)
        throw std::runtime_error("invalid password policy (new)");

    return { key, one_based_key_pos_1 - 1, one_based_key_pos_2 - 1 };
}

int main()
{
    auto file = std::ifstream("data.txt");
    
    auto valid_old = std::size_t{ 0 };
    auto valid_new = std::size_t{ 0 };
    
    for (auto entry = Entry(); file >> entry; )
    {
        if (old_auth::is_password_valid(entry.password, make_old_auth_policy(entry.key, entry.a, entry.b)))
            ++valid_old;
        
        if (new_auth::is_password_valid(entry.password, make_new_auth_policy(entry.key, entry.a, entry.b)))
            ++valid_new;
    }
    
    std::cout << "Part One: " << valid_old << "\n" << "Part Two: " << valid_new << "\n";
}

(not properly tested).

\$\endgroup\$
1
  • \$\begingroup\$ Thanks. Many of these changes are applicable to my Rust code as well, especially the policy part - I was just feeling lazy at that time, so I added a policy parameter instead of making a proper class. \$\endgroup\$
    – L. F.
    Commented Feb 2, 2021 at 2:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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