//Fun/AdventCalendar2020/Day2-2.cpp //Matthew Ellison // Created: 12-02-20 //Modified: 12-02-20 //Find the two entries that sum to 2020 and then multiply those two numbers together #include #include #include #include #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 importData(){ std::vector 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 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 */