Files
AdventOfCode2020/Day4-1.cpp
2020-12-04 21:33:18 -05:00

135 lines
3.0 KiB
C++

//Fun/AdventCalendar2020/Day4-1.cpp
//Matthew Ellison
// Created: 12-04-20
//Modified: 12-04-20
//Validate passport data
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include "Stopwatch.hpp"
#include "Algorithms.hpp"
struct passport{
std::string birthYear;
std::string issueYear;
std::string expirationYear;
std::string height;
std::string hairColor;
std::string eyeColor;
std::string passportId;
std::string countryId;
//Returns true if the passport is valid
bool isValid(){
if(validString(birthYear) && validString(issueYear) && validString(expirationYear) && validString(height) && validString(hairColor) && validString(eyeColor) && validString(passportId)){
return true;
}
else{
return false;
}
}
//Returns true if the string is a valid string
bool validString(std::string str){
if(!str.empty()){
return true;
}
else{
return false;
}
}
};
std::vector<passport> importData(){
std::vector<passport> passports;
std::ifstream inputFile;
inputFile.open("inputs/Day4.txt"); //Open the file that has the input for the question
//Get the input one line at a time because a full blank line is the end of a passport
while(!inputFile.eof()){
passport currentPassport;
std::string currentLine;
std::getline(inputFile, currentLine);
while(currentLine != ""){
//Split the string on [space]
for(std::string str : mee::split(currentLine, ' ')){
//Split the string on :
std::vector<std::string> fields = mee::split(str, ':');
std::string field = fields[0];
std::string value = fields[1];
//Determine what field you are dealing with and save the data
if(field == "byr"){
currentPassport.birthYear = value;
}
else if(field == "iyr"){
currentPassport.issueYear = value;
}
else if(field == "eyr"){
currentPassport.expirationYear = value;
}
else if(field == "hgt"){
currentPassport.height = value;
}
else if(field == "hcl"){
currentPassport.hairColor = value;
}
else if(field == "ecl"){
currentPassport.eyeColor = value;
}
else if(field == "pid"){
currentPassport.passportId = value;
}
else if(field == "cid"){
currentPassport.countryId = value;
}
else{
std::cout << "ERROR!\n" << "field = " << field << "\tValue = " << value << std::endl;
exit(1);
}
}
std::getline(inputFile, currentLine);
}
passports.push_back(currentPassport);
}
return passports;
}
int main(){
mee::Stopwatch timer;
int validPassports = 0;
//Start the timer
timer.start();
//Get the passport data
std::vector<passport> passports = importData();
//Count how many are valid
for(passport pspt : passports){
if(pspt.isValid()){
++validPassports;
}
}
//Stop the timer
timer.stop();
//Print the results
std::cout << "There are " << validPassports << " valid passports"
<< "\nIt took " << timer.getStr() << " to finish this problem" << std::endl;
return 0;
}
/* Results:
There are 228 valid passports
It took 1.999 milliseconds to finish this problem
*/