116 lines
2.5 KiB
C++
116 lines
2.5 KiB
C++
//Fun/AdventCalendar2020/Day2-1.cpp
|
|
//Matthew Ellison
|
|
// Created: 12-02-20
|
|
//Modified: 12-02-20
|
|
//Count the number of valid passwords according to their policy:
|
|
//{char} must appear in {password} >= {minNum} and <={maxNum}
|
|
//{minNum}-{maxNum} {char}: {password}
|
|
|
|
|
|
#include <iostream>
|
|
#include <fstream>
|
|
#include <string>
|
|
#include <vector>
|
|
#include "Stopwatch.hpp"
|
|
|
|
|
|
struct pswd{
|
|
int minTimes;
|
|
int maxTimes;
|
|
char character;
|
|
std::string password;
|
|
|
|
bool isValid(){
|
|
//Count the number of times the character appears in the password
|
|
int count = 0;
|
|
for(char ch : password){
|
|
if(ch == character){
|
|
++count;
|
|
}
|
|
}
|
|
//If the character appeared >= mintimes and <= maxTimes return true
|
|
return ((count >= minTimes) && (count <= maxTimes));
|
|
}
|
|
};
|
|
|
|
|
|
std::vector<pswd> importData(){
|
|
std::vector<pswd> passwords; //Holds the info about all of the passwords
|
|
std::ifstream inputFile;
|
|
inputFile.open("inputs/Day2.txt");
|
|
|
|
//Loop until you find the end of the file
|
|
while(!inputFile.eof()){
|
|
std::string currentLine; //Holds the current line
|
|
pswd newPassword; //Holds the info about the current password
|
|
|
|
|
|
//Read the #-# into a string
|
|
inputFile >> currentLine;
|
|
|
|
//Break the string apart into two numbers
|
|
std::string minTimesStr;
|
|
std::string maxTimesStr;
|
|
int stringLoc = 0;
|
|
while(isdigit(currentLine[stringLoc])){
|
|
minTimesStr += currentLine[stringLoc++];
|
|
}
|
|
//Skip the -
|
|
++stringLoc;
|
|
while(isdigit(currentLine[stringLoc])){
|
|
maxTimesStr += currentLine[stringLoc++];
|
|
}
|
|
//Turn those strings into ints
|
|
newPassword.minTimes = std::stoi(minTimesStr);
|
|
newPassword.maxTimes = std::stoi(maxTimesStr);
|
|
|
|
|
|
//Get the letter to look for
|
|
inputFile >> currentLine;
|
|
|
|
//Get just the first character
|
|
newPassword.character = currentLine[0];
|
|
|
|
|
|
//Get the password
|
|
inputFile >> currentLine;
|
|
newPassword.password = currentLine;
|
|
|
|
|
|
//Add the new password to the array
|
|
passwords.push_back(newPassword);
|
|
}
|
|
return passwords;
|
|
}
|
|
|
|
int main(){
|
|
mee::Stopwatch timer;
|
|
int validPasswords = 0;
|
|
//Get the data from the file
|
|
std::vector<pswd> passwords = importData();
|
|
|
|
//Start the timer
|
|
timer.start();
|
|
|
|
//Find how many of the passwords are valid
|
|
for(pswd password : passwords){
|
|
if(password.isValid()){
|
|
++validPasswords;
|
|
}
|
|
}
|
|
|
|
//Stop the timer
|
|
timer.stop();
|
|
|
|
//Print the results
|
|
std::cout << "The number of valid passwords in the file is " << validPasswords
|
|
<<"\nIt took " << timer.getStr() << " to finish this problem" << std::endl;
|
|
|
|
return 0;
|
|
}
|
|
|
|
/* Results:
|
|
The number of valid passwords in the file is 572
|
|
It took 0.000 nanoseconds to finish this problem
|
|
*/
|