Files
AdventOfCode2020/Day2-2.cpp
2020-12-03 09:53:12 -05:00

121 lines
2.6 KiB
C++

//Fun/AdventCalendar2020/Day2-2.cpp
//Matthew Ellison
// Created: 12-02-20
//Modified: 12-02-20
//Count the number of valid passwords accoring to the policies
//{char} must appear in password at either {firstLoc} or {secondLoc} but not both (xor)
//{firstLoc}-{secondLoc} {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(){
bool firstLocation = false;
bool secondLocation = false;
//Check the first location
if(password[minTimes - 1] == character){
firstLocation = true;
}
//Check the second location
if(password[maxTimes - 1] == character){
secondLocation = true;
}
//Return firstLocation xor second location
return firstLocation ^ secondLocation;
}
};
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 306
It took 0.000 nanoseconds to finish this problem
*/