Skip to content

Instantly share code, notes, and snippets.

@orendon
Created December 4, 2020 06:54
Show Gist options
  • Save orendon/6bd673632f87c08b55927ba7ceb23000 to your computer and use it in GitHub Desktop.
Save orendon/6bd673632f87c08b55927ba7ceb23000 to your computer and use it in GitHub Desktop.
Advent of Code 2020 - Day 04
#include <iostream>
#include <string>
#include <regex>
#include <map>
using namespace std;
const string BYR = "byr:";
const string IYR = "iyr:";
const string EYR = "eyr:";
const string HGT = "hgt:";
const string HCL = "hcl:";
const string ECL = "ecl:";
const string PID = "pid:";
map<string, string> fields = {
{BYR, "(\\d{4})\\D"},
{IYR, "(\\d{4})\\D"},
{EYR, "(\\d{4})\\D"},
{HGT, "([0-9]+)(in|cm)"},
{HCL, "#[0-9a-f]{6}\\D"},
{ECL, "(amb|blu|brn|gry|grn|hzl|oth)"},
{PID, "\\d{9}\\D"},
};
bool is_present(string &str){
for(auto &[f, p] : fields){
if (str.find(f) == string::npos)
return false;
}
return true;
}
bool is_valid(string str){
for(auto &[f, p] : fields){
regex pattern(f+p);
smatch match;
regex_search(str, match, pattern);
if(match.empty()) return false;
int num;
if (f == BYR){
num = stoi(match[1]);
if (num<1920 or num>2002) return false;
} else if (f == IYR){
num = stoi(match[1]);
if(num<2010 or num>2020) return false;
} else if (f == EYR){
num = stoi(match[1]);
if(num<2020 or num>2030) return false;
} else if (f == HGT){
num = stoi(match[1]);
if(match[2]=="cm" and (num<150 or num>193)) return false;
if(match[2]=="in" and (num<59 or num>76)) return false;
}
}
return true;
}
int main() {
string passport = "", line;
int part1_answer = 0, part2_answer = 0;;
while(getline(cin, line)){
if (line == ""){
if (is_present(passport)) part1_answer++;
if (is_valid(passport)) part2_answer++;
passport = "";
} else {
passport += (line + " ");
}
}
if (is_present(passport)) part1_answer++;
if (is_valid(passport)) part2_answer++;
cout << "Part 1: " << part1_answer << "\n";
cout << "Part 2: " << part2_answer << "\n";
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment