Advent-of-Code/2020/2/main.cpp

73 lines
1.6 KiB
C++
Raw Permalink Normal View History

#include <algorithm>
#include <fstream>
#include <iostream>
#include <string>
// 6-7 w: wwhmzwtwwk
bool Valid1(const std::string &str)
{
int min, max;
char letter;
std::string password;
auto dash = str.find('-');
auto space = str.find(' ');
auto space_two = str.find(' ', space + 1);
min = std::atoi(str.substr(0, dash).c_str());
max = std::atoi(str.substr(dash + 1, space).c_str());
letter = str.at(space + 1);
password = str.substr(space_two + 1);
// std::cout << "min: " << min << std::endl
// << "max: " << max << std::endl
// << "letter: " << letter << std::endl
// << "pass: " << password << std::endl;
int total = std::count(password.begin(), password.end(), letter);
return (total >= min && total <= max);
}
bool Valid2(const std::string &str)
{
int min, max;
char letter;
std::string password;
auto dash = str.find('-');
auto space = str.find(' ');
auto space_two = str.find(' ', space + 1);
min = std::atoi(str.substr(0, dash).c_str());
max = std::atoi(str.substr(dash + 1, space).c_str());
letter = str.at(space + 1);
password = str.substr(space_two + 1);
bool a = password[min - 1] == letter;
bool b = password[max - 1] == letter;
return a != b;
}
int main()
{
std::ifstream ifs("data");
if(!ifs.is_open())
return -1;
int valid1 = 0;
int valid2 = 0;
for(std::string line; std::getline(ifs, line); )
{
if(Valid1(line))
++valid1;
if(Valid2(line))
++valid2;
}
std::cout << valid1 << " valid1 passwords." << std::endl;
std::cout << valid2 << " valid2 passwords." << std::endl;
return 0;
}